How do I remove all the groups from disabled Active Directory Users via Powershell?

2.1k views Asked by At

I'm trying to gather all the disabled users in our Active Directory and trying to remove the disabled users from all their groups. Mostly for cleanup purposes. I'm a bit stuck on my script. I'm not sure what to put after Remove-ADPrincipalGroupMembership:

$disabled_users = Get-AdUser -SearchBase "Ou=Users, Ou=test, DC=testdomain, DC=io" -Filter
  "enabled -eq 'false'"
 foreach($person in $disabled_users) {
     Get-ADPrincipalGroupMembership $person | Remove-ADPrincipalGroupMembership #stuckhere
 }
2

There are 2 answers

1
Cpt.Whale On

Get-ADPrincipalGroupMembership returns only groups, leading Remove-ADPrincipalGroupMembership to auto-fill -Identity with the group name. You'll have to re-use the user object in -Identity.

Because of the first issue, Remove-ADPrincipalGroupMembership doesn't accept multiple groups from the pipeline. It should normally, but the [ADGroup] objects returned by Get-ADPrincipalGroupMembership seem to trip it up. To fix, use a ForEach loop, or use a two-step process:

# two steps:
$groups = Get-ADPrincipalGroupMembership $person
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $groups -WhatIf 

# OR foreach loop:
Get-ADPrincipalGroupMembership $person | 
    Foreach { 
        Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $_
    }

Note that you can't remove an AD user's primary group (usually 'Domain Users'), so you may want to add a filter:

$groups = Get-ADPrincipalGroupMembership $person |
    Where Name -notlike 'Domain Users'
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $groups
0
Santiago Squarzon On

Adding another option using Remove-ADGroupMember instead:

Get-ADPrincipalGroupMembership $person | Remove-ADGroupMember -Members $person

Remove-ADGroupMember will take the distinguishedNames of the user's membership as pipeline value so you only need to specify the Member of the group you want to remove.