1

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
 }
dbc
  • 104,963
  • 20
  • 228
  • 340

2 Answers2

0

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
Cpt.Whale
  • 4,784
  • 1
  • 10
  • 16
  • @SantiagoSquarzon - Rather than editing [this answer](https://stackoverflow.com/a/67200713/3744182) to include `Remove-ADGroupMember`, consider adding your own answer, as the edit may get rejected for conflicting with the author's intent. – dbc Apr 22 '21 at 14:46
0

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.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37