Forum Discussion
Remove groups from a user with an exception
Hey,
I am trying to remove a number of users from all of their group memberships, with the exception of one group. I've been working on this for an hour or so and hit a stumbling block:
$username="User01"
$groupdntoexclude=(get-adgroup "group 1").distuishedname
get-aduser -identity $username -properties MemberOf | where-object -ne $groupdntoexclude | for-eachObject { $_.MemberOf | remove-adgroupmember -members $username -confirm:$true}
So far all I seem to be able to do is remove the user for every group. I've tried playing around with the Where-Object conditions but can't quite get it right. Any suggestions would be greatly appreciated!
Thanks,
Matt
Matt_P_Standing I changed it a little bit and added the possibility for more usernames
$usernames = "User01", "User02" $groupdntoexclude = (Get-ADGroup -Identity "Group 1").DistinguishedName foreach ($username in $usernames) { foreach ($group in (Get-ADUser -Identity $username -properties MemberOf).MemberOf) { if ($group -ne $groupdntoexclude) { Write-Host ("Removing {0} membership from user {1}" -f $group, $username) Remove-ADGroupMember -Identity $group -Members $username -Confirm:$true } } }
4 Replies
- Did that work out for you?
- Matt_P_StandingBrass Contributor
Harm_Veenstra Sorry for the delay in replying, my virtual lab died and I had to rebuild it before I could test the script.
It works perfectly thank you. I like the approach!
- No worries, I hope the virtual lab is back and kicking 🙂
Matt_P_Standing I changed it a little bit and added the possibility for more usernames
$usernames = "User01", "User02" $groupdntoexclude = (Get-ADGroup -Identity "Group 1").DistinguishedName foreach ($username in $usernames) { foreach ($group in (Get-ADUser -Identity $username -properties MemberOf).MemberOf) { if ($group -ne $groupdntoexclude) { Write-Host ("Removing {0} membership from user {1}" -f $group, $username) Remove-ADGroupMember -Identity $group -Members $username -Confirm:$true } } }