Home > Software engineering >  PowerShell: Foreach for array in Where-Object to verify match on property
PowerShell: Foreach for array in Where-Object to verify match on property

Time:09-28

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.

CodePudding user response:

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
}
  • Related