This requirement can be achieved in two directions.
1. Find the disabled account and delete all the groups except domain users, the script content is as follows
#导入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, find the disabled account sAMAccountName and group, the group outside the domain users through sAMAccountName delete members, the content is as follows
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
}
Query the OU for disabled ad accounts through PowerShell and delete their owning group