2021 Jun 13
Remove the User from a Group if They are the Members of Another One
12:04 - By Andrii Dykhlin - ActiveDirectory - Permalink
If you need to remove the user from a particular group based on the membership of another, you can do that super easy, barely an inconvenience.
For that, we need a short PowerShell script, like the one below. I won't use any particular names, you can put your own of course.
$groupA = Get-ADGroupMember -Identity "Group 1" -Recursive | Select-Object -ExpandProperty samaccountname
$groupB = Get-ADGroupMember -Identity "Group 2" -Recursive | Select-Object -ExpandProperty samaccountname
foreach ($user in $groupA) {
If ($groupB -contains $user) {
Write-Host "$user is a member of both groups, removing from the second one"
Remove-ADGroupMember -Identity "Group 2" -Member $user -Confirm:$false
}
}
We set up that $groupA and $groupB contain the list of samaccountnames of their members, after that we check each user in $groupA list for being a member of the $groupB as well. We can check both groups for the same user, but if we're checking all the members of groupA, that pretty much means they are already there, so the extra check is not that important.
On the next line we just notify ourselves the user is going to be removed from the group, and the last line removes the user indeed. And -Confirm:$false is used to make a more flawless automation: if you need to remove 100 users, you will need to confirm every user from the group removal, which might be time-consuming. If you need to ensure nothing is going wrong, you can remove that part and confirm every user manually.