I recently wanted to remove groups from (almost all) disabled users so I wrote my own set of functions in PowerShell v3 (which doesn’t require third-party software).
For composability and re-use, I first wrote a function to remove the specified user from all groups (aside from their primary group). I could add an option to specify the group type (Security or Distribution) but I don’t need that functionality at the moment.
Function Remove-UserFromGroups ($User) {
$PrimaryGroup = (Get-ADUser $User -Properties PrimaryGroup).PrimaryGroup
Get-ADPrincipalGroupMembership $User |
ForEach-Object {
If ($_.distinguishedName -ne $PrimaryGroup) {
Write-Output "Removing ‘$($User.Name)’ from ‘$_’"
Remove-ADGroupMember $_ -Members $User # -Confirm:$False
}
}
}
I then used this function to remove all disabled users from all groups (other than their primary group). I use a search base so that an OU can be specified and I also have a list of default/system users who should not have their group membership changed.
Function Remove-DisabledUsersFromGroups (
$SearchBase = 'OU=department,DC=example,DC=com',
$ExcludedUsers = @('krbtgt', 'SUPPORT_388945a0', 'Guest')
) {
Get-ADUser -Filter { Enabled -eq $False } -SearchBase $SearchBase |
Where { $_.Name -notin $ExcludedUsers } |
ForEach-Object {
Remove-UserFromGroups $_
}
}