Farrukh Waheed
Farrukh Waheed

Reputation: 2193

PowerShell: Comparing Object stored in an array result unequal

In following code sample, the comparison of original object with its stored copy in an array results in unequal status. I want to understand this phenomena why they are not equal:

$MyArray=@()
$MyCFG="" | Select-Object -Property ProjName,ProCFG

$MyCFG.ProjName="p1"
$MyCFG.ProCFG="c1"
$MyArray+=$MyCFG.PsObject.Copy()

$MyCFG.ProjName="p2"
$MyCFG.ProCFG="c2"
$MyArray+=$MyCFG.PsObject.Copy()

$MyCFG.ProjName="p3"
$MyCFG.ProCFG="c3"
$MyArray+=$MyCFG.PsObject.Copy()


ForEach($obj in $MyArray)
{
    if ($MyCFG -eq $obj)
    {Write-Host "Equal"}
    else
    {Write-Host "Unequal"}

}

The last object values i.e. $MyCFG.ProjName="p3" and $MyCFG.ProCFG="c3" are supposed to be same as stored in $MyArray, but they results in Unequal as well.

Although, it can compare properly by comparing its property values i.e:

if (($MyCFG.ProjName -eq $obj.ProjName) -and ($MyCFG.ProCFG -eq $obj.ProCFG))

but wondering why Objects comparison results as unequal...

Upvotes: 2

Views: 8934

Answers (1)

CB.
CB.

Reputation: 60956

You can use compare-object in this way

ForEach($obj in $MyArray)
{ 
    if (compare-object $obj $mycfg -Property Projname,procfg)
    {Write-Host "Unequal"}
    else
    {Write-Host "Equal"}
}

Comparing the properties you need ( all in this case ) and test if there's some difference.

Upvotes: 4

Related Questions