2

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...

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

+1 Another note for the OP: instead of explicitly writing the result to host, you could take advantage of Compare-Object not returning anything when it is true to return a boolean instead: @(Compare-Object $obj $MyCFG -Property projname,procfg).Length -eq 0
@HyperAnthony Try the code with my solution: there is not output from the compare-object in any conditions..
Right, it wasn't necessarily speaking to your example but I wanted to offer OP some usage advice for Compare-Object as they would hopefully follow-up on this answer by experimenting a bit with the cmdlet. (Like what would happen if it wasn't embedded in an if statement)
@HyperAnthony hu.. ok! My misunderstanding ;)
There are parameters to Compare-Object to tell it to output various combinations of Left-Only, Right-Only, or Both

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.