Reputation: 29159
I have an array
$a = (Invoke-RestMethod -Uri "...." -Method Get) | select X,Y,Z # Object[] Z has type of datetime
$a
has X, Y, Z
.
Now I need to check if a row is in $a
$x,$y,$z = ....
if ($a -contains $x,$y, $x) { ... } # doesn't work
How to do it?
Upvotes: 1
Views: 654
Reputation: 438198
It sounds like you want to test array $a
for containing an object that has a given set of property values ($x
, $y
, $z
) for a given set of property names (.X
, .Y
, .Z
):
$hasObjectWithValues = [bool] $(foreach ($o in $a) {
if ($o.X -eq $x -and $o.Y -eq $y -and $o.Z -eq $z) {
$true
break
}
})
Note: The cleaner form [bool] $hasObjectWithValues = foreach ...
should work, but, as of PowerShell Core 7.0.0-preview.4, doesn't, due to this bug
As for what you tried:
$a -contains $x,$y, $z
The RHS of PowerShell's -contains
operator only supports a scalar (single value), to be tested for equality with the elements in the the array-valued LHS.
However, even if you wrapped your RHS into a single object - [pscustomobject] @{ X = $x, Y = $y, Z = $z }
, that approach wouldn't work, because [pscustomobject]
s, as also returned by Invoke-RestMethod
, are reference types, which - in the absence of custom equality comparison behavior - are compared by reference equality, meaning that they're only considered equal if they refer to the very same object in memory.
Upvotes: 1