在变量属性上过滤Where-Object

时间:2019-01-10 17:45:37

标签: powershell

阅读以下答案: (Where object based on a variable content),(Use array of strings for comparing in Where-Object in PowerShell

$allgroups
DisplayName
--------
Group1
Group2
Group3

$mailgroups
DisplayName
--------
Group1
Group3

$newgroup = $allgroups | ? ($_.DisplayName -notin $mailgroups)
$newgroup = $allgroups | ? ($_.DisplayName -notin ($mailgroups | Select DisplayName))

$ newgroup应该=“ DisplayName:Group2”,以上命令返回null。尝试过其他运算符:

-ne, -cnotin, -eq, -notcontains

1 个答案:

答案 0 :(得分:2)

您的语法错误:

$newgroup = $allgroups | ? DisplayName -notin $mailgroups.DisplayName

或者如果您想保持自己的方式:

$newgroup = $allgroups | Where-Object { $PSItem.DisplayName -notin $mailgroups.DisplayName }

或者,对于v2:

$newgroup = $allgroups | Where-Object {
    ($mailgroups | Select-Object -ExpandProperty DisplayName) -notcontains $_.DisplayName
}

脚注:$PSItem$_相同; $PSItem在第3版中引入。此外,?Where-Object的默认别名。