Clearing out Groups

Do you need to clear out a users groups in one go. It’s easy.

(Get-aduser -Identity testman -Properties memberof).MemberOf | sort | ForEach-Object {(get-adgroup -Identity $_ -properties samaccountname).samaccountname | Remove-ADGroupMember -Members testman -Confirm:$false}

A single line, that’s right. A single line. So lets break it down

(Get-aduser -Identity testman -Properties memberof).MemberOf

This part grabs all of the group members. By default the memberof is in DistinguishedName formation. Thus, you can pipe it into the get-adgroup easily without any issues.

| sort |

This part sorts the outcome of the memberof. This way you can see what’s going on that is kind of cool. Piping into the sort is optionial.

ForEach-Object {(get-adgroup -Identity $_ -properties samaccountname).samaccountname | Remove-ADGroupMember -Members testman -Confirm:$false}

Then we pipe the sorted information into a foreach-object loop. We first grab the groups information with the get-adgroup. We want the samaccountname because Remove-adgroupmember doesn’t understand a
DistinguishedName.

(get-adgroup -Identity $_ -properties samaccountname).samaccountname

Then we pipe that information into a remove-adgroupmember command. If you notice it only has members and confirm. The member is the original username and the confirm is set to false.

| Remove-ADGroupMember -Members testman -Confirm:$false}

That’s it! Crazy right? If you want to see it happen, do a verbose.

State of warning, you will see an error pop up. That error is the default group.