1

Good day, it´s a little hard to explain what I want to do, for that reason I did added code what I´m looking for.

$IDFilterList = @("1" , "2", "3", "4", "5", "6", "7", "8", "9")
   
    if ($file.Name.Contains("SomeStuff")) {
        $ImportendCollection += $Result | 
        Where-Object { ($_.Level -Match 1) -or ($_.Level -Match 2) -or ($_.Level -Match 3) |
        **** Where-Object { foreach ($id in $IDFilterList) {($_.ID -Match $id)}} |
        Group-Object -Property id, LevelDisplayName, LogName -NoElement | 
        Sort-Object -Property count -Descending
    }

I know that this code isn´t correct in the line with the "stars", but it should explain what i want to do. How must this line be look like correctly?

  Where-Object { foreach ($id in $IDFilterList) {($_.ID -Match $id)}} |

Thanks for your help.

5
  • You want to test whether $IDFilterList contains the value of $_.ID? Commented Sep 27, 2021 at 15:09
  • Since we have no clue what the variables $file, $ImportendCollection, $Result etc. are about, this would be very hard to answer. Please edit your question and tell us what it all means Commented Sep 27, 2021 at 15:10
  • Looks like you don't actually need -match: Where-Object {$_.Level -in 1,2,3 -and $_.ID -in $IDFilterList } Commented Sep 27, 2021 at 15:11
  • @MathiasR.Jessen this was perfectly what i was looking for and it works like a charm! How can i flag it as "solution"? Commented Sep 27, 2021 at 18:20
  • @Larry That's great! I've posted a proper answer below, click the checkmark on the left of it to accept it :) Commented Sep 27, 2021 at 18:38

1 Answer 1

1

In this particular case you don't actually need to nest Where-Object - since you're looking for exact matches, you might as well use the -contains or -in operators:

... |Where-Object { $_.Level -in 1,2,3 -and $_.ID -in $IDFilterList }
# or
... |Where-Object { 1,2,3 -contains $_.Level -and $IDFilterList -contains $_.ID }

For reference, the .Where() extension method is often a good tool for nesting filter clauses - it works just like Where-Object, but it supports different filtering modes, including it's First mode which provides for "early exit" once a match is found:

... |Where-Object {
        # assign ID property value to local variable
        $ID = $_.ID
        # Test whether any entries in $IDFilterList is a matching pattern for $ID
        $IDFilterList.Where({ $ID -match $_ }, 'First').Count -gt 0
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your input. It looks like to me that powershell is much more similar to C# than i thought. Your post is exactly what i was looking for and works how you expected!

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.