这个需求可以通过两个方向来实现
1、找到禁用的账号,删除除domain users外的所有组,脚本内容如下
#导入AD模块
import-module ActiveDirectory
#被禁用户
$users = get-aduser -Filter * -SearchBase "OU=xxx,DC=xxx,DC=com" | foreach {if ($.enabled -eq $false){echo $.Name} }
#删除用户所有组
foreach($user in $users)
{
$Membership = Get-ADPrincipalGroupMembership $User
$group = $Membership.distinguishedName -ne "CN=Domain Users,CN=Users,DC=xxx,DC=com"
Remove-ADPrincipalGroupMembership -identity $User -MemberOf $group -confirm:$False
}
2、找到禁用账号的samaccountname跟组,将domain users外的组通过samaccountname删除成员,内容如下
import-module ActiveDirectory
$users = get-aduser -filter 'enabled -eq $false' -Properties samaccountname, memberof -SearchBase "OU=xxx,DC=xxx,dc=com" | select samaccountname,
@{ n = 'MemberOf'; e = { ($.memberof | % { (Get-ADObject $).Name }) -join "," } }
foreach ($user in $users)
{
Get-ADGroup -Filter { name -notlike "domain users" } | Remove-ADGroupMember -Members $user.samaccountname -Confirm:$False
}