PSCustomObject - use contains filter on array

341 Views Asked by At

i am trying to figure out how i can search a value in an array that is in a pscustomobject.

$global:RuleSet+= [pscustomobject][ordered]@{  RuName="NSMS" ;
                                               Agent=("ABC",  
                                                      "DFG",
                                                      "HIJ")}
$search = "ABC"

$myRuleSet = $RuleSet | Where-Object { $search -contains $_.Agent } 

This was my attempt to solve the problem, but it dosn't seem to work that way. Can someone please explain to my how this could or should be done?

1

There are 1 best solutions below

5
On

You have the operands the wrong way around - $_.Agent resolves to the collection, so it should be the left-hand side of the -contains operation:

$global:RuleSet += [pscustomobject]@{
  RuName = "NSMS"
  Agent = @("ABC","DFG","HIJ")
}

$search = "ABC"

$myRuleSet = $RuleSet | Where-Object { $_.Agent -contains $search }

Note: [ordered] is unnecessary when using [pscustomobject]@{ ... } instantiation syntax.

Now that the property reference is on the left-hand side, we can rewrite the Where-Object statement to use its simpler property syntax:

$myRuleSet = $RuleSet | Where-Object Agent -contains $search