Search code examples
arrayspowershellcompareobject

Assigning values to the an array after using Compare-Object


I have been trying to assign values of Compare-Object results but i am getting additional informations on the output.

Here is the code:

$a = (dir C:\_pc\*).BaseName
$b = (dir C:\Users\username\Documents\folder\Jezyki\*).BaseName
$c = (Compare-Object -IncludeEqual -ExcludeDifferent $a $b)
foreach ($element in $c) {
"$element"
}
Write-Output ($c)

Example output of runing this script:

@{InputObject=FolderName; SideIndicator===}

Solution

  • Try the -PassThru switch for Compare-Object. It will output the strings. If the object was an object, it would append sideindicator as an extra property.

    Ex.

    $c = Compare-Object -IncludeEqual -ExcludeDifferent $a $b -PassThru
    

    Also, if you would like to keep the original FileInfo-object, you could specify -Property Basename to compare that value only without throwing away the rest of the object. Ex.

    $c = Compare-Object (dir C:\_pc\*) (dir C:\Users\username\Documents\folder\Jezyki\*) -IncludeEqual -ExcludeDifferent -Property Basename -PassThru