Reputation: 95
In my Powershell script two variables get value through sql query, even though there input value seems to be same the if condition is returning false instead of true.
If Equal condition doesn't work with System-Objects, what condition can I use to check if they are equal or not?
Below is Powershell script part:
Echo "first_result:$first_result,second_result:$second_result"
Echo ""
if($first_result -eq $second_result){
Echo "True"
}
else{
Echo "False"
}
Echo ""
$first_result.getType()
$second_result.getType()
I have tried other comparison operators -like , -match. Even tried Trim() function, but nothing worked.
I found this topic of java bit similar but didn't get much help for powershell: Why .equals method is failing on two same value objects?
Upvotes: 2
Views: 6105
Reputation: 36738
You are trying to compare two arrays. The equality operator -eq
works just fine, but it does a reference comparison while you are looking for a value comparison, i.e. do the contents of the two arrays match? The easiest way to do that is with Compare-Object
, which returns an array of differences between the two arrays. If there are no differences, then it returns $null. So you just need to examine the length of the result to check for value equality:
$arraysMatch = @(Compare-Object $first_result $second_result).Length -eq 0
Note that Compare-Object by default compares its arguments in an order-independent fashion, thus 1,3,2 will match 1,2,3. If you want to compare them taking order into account, add the SyncWindow
parameter:
$arraysMatch = @(Compare-Object $first_result $second_result -SyncWindow 0).Length -eq 0
Upvotes: 2
Reputation: 839
-eq is similar to == operator which will compare the address for Objects not values. You must use Array or other collection utilities to compare two Objects.
Upvotes: 1