1

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?

3
  • Try piping the select to Get-Member to see what properties are available. Commented Oct 2, 2019 at 22:21
  • $a has X, Y, Z Commented Oct 2, 2019 at 22:22
  • You'll have to share what the data is and what you expect as a return. Commented Oct 2, 2019 at 23:02

1 Answer 1

1

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.

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

1 Comment

@ca9163d9: My bad - I forgot about this bug, which didn't surface in my informal tests. Please try my update.

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.