PowerShell: Foreach for数组在Where-Object上验证匹配属性



大家好!解释我想做什么有点困难,因此我添加了我正在寻找的代码。

$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
}

我知道这段代码在"星号"行中是不正确的,但它应该解释了我想做的事情。这条线应该是什么样子呢?

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

谢谢你的帮助。

在这种特殊情况下,您实际上不需要嵌套Where-Object-因为您正在寻找精确匹配,您不妨使用-contains-in操作符:

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

作为参考,.Where()扩展方法通常是嵌套过滤子句的好工具-它的工作原理与Where-Object一样,但它支持不同的过滤模式,包括提供"提前退出"的First模式;一旦找到匹配项:

... |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
}

最新更新