PowerShell:用于 Where-Object 中数组的 Foreach 以验证 属性 上的匹配
PowerShell: Foreach for array in Where-Object to verify match on property
美好的一天,
有点难以解释我想做什么,因此我确实添加了我正在寻找的代码。
$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
}
美好的一天, 有点难以解释我想做什么,因此我确实添加了我正在寻找的代码。
$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
}