powershell 结合 where 和 or

powershell combine where and or

我正在尝试构建一个脚本以根据用户主体名称排除用户。我从以下脚本开始

Get-MsolUser -all | ?{($_.userprincipalname -notlike "*@domain1.com" -or $_.userprincipalname -notlike "*@domain2.com" -or $_.userprincipalname -notlike "*domain3.com")}

上面的代码没有排除任何用户,它只是忽略了 where 语句

BR 卡洛斯

如果后缀是 @domain2.com,其他两个子句仍然是 true(因为 @domain2.com 仍然是 而不是 @domain1.com@domain3.com),因此您需要使用 -and 而不是 -or:

Get-MsolUser -all | ?{($_.userprincipalname -notlike "*@domain1.com" -and $_.userprincipalname -notlike "*@domain2.com" -and $_.userprincipalname -notlike "*domain3.com")}

其他解决方案,带有域列表:

$ExcludeDomain=@('domain1.com', 'domain2.com', 'domain3.com')

Get-MsolUser -all | where {($_.userprincipalname -split '@')[1] -notin $ExcludeDomain}