0

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for the explaination. But after trying it out it still does not work. I've tried it with an eympt fresh script, no luck either. It does not seem to match for some reason. Any idea?
@pyte perhaps you forgot to create the $RuleSet array/list? $global:RuleSet = @()
@ Mathias R. Jessen No this would result in an error. I've created it in my script with $global:RuleSet2 = @() EDIT: Made a Typo in the Ruleset! Sorry :-) That fixed it!
@pyte RuleSet and RuleSet2 are 2 different variable names, they won't resolve to the same thing
Made a Typo in the Ruleset! Sorry :-) That fixed it! RuleSet2 was from the testscript sorry for not clarifying it

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.