Powershell-如果用户不是多个组的成员,则将其从OU添加到安全组



我正在编写一个脚本,以检查特定OU的用户是否不是组1、组2、组3或组4的成员。

我已经尝试过了,但有些用户被列出了,而他们不应该被列出。

get-aduser -filter * -searchbase "$Ou" | where-object {((get-aduser $_.samaccountname -properties memberof).memberof -ne "$grp1") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp2") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp3") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp4")} | Select SamAccountName

不确定我是否理解,但听起来你在要求这样的东西:

$ou = 'OU=crowleytest,DC=contoso,DC=local'
$group1 = 'CN=group1,OU=crowleytest,DC=contoso,DC=local'
$group2 = 'CN=group2,OU=crowleytest,DC=contoso,DC=local'
$group3 = 'CN=group3,OU=crowleytest,DC=contoso,DC=local'
$group4 = 'CN=group4,OU=crowleytest,DC=contoso,DC=local'
$users = Get-ADUser -SearchBase $ou -Filter * -Properties memberof
$results = $users | where {
$_.memberof -notcontains $group1 -and
$_.memberof -notcontains $group2 -and
$_.memberof -notcontains $group3 -and
$_.memberof -notcontains $group4
}
$results

e-这个过滤器也可以向左移动到-filter参数中以获得更好的性能,但这需要不同的语法。如果您不使用庞大的用户列表,那么上面的示例就足够了。

最新更新