PowerShell - Finding all of users' group memberships and kicking it out of them
as title says, I have to find all the groups that the user is a member of, and deleting its membership from all of them.
I've tried this:
get-adgroup -filter * | where {(Get-ADGroupMember $_ | foreach {$_.PrimarySmtpAdress}) -contains "[email protected]"}
but it doesnt return anything (although THERE ARE some items that have to be returned)
as for the deletion I found no way to do it, could someone give me an example of a code that does this?
Im talking about security groups.
Assuming that all backlinks are in place, this is a simple 3-step process easily done with powershell:
# 1. Retrieve the user in question:
$User = Get-ADUser "username" -Properties memberOf
# 2. Retrieve groups that the user is a member of
$Groups = $User.memberOf |ForEach-Object {
Get-ADGroup $_
}
# 3. Go through the groups and remove the user
$Groups |ForEach-Object { Remove-ADGroupMember -Identity $_ -Members $User }
If you don't want to manually confirm removing the user for each group, use -Confirm:$false
:
Remove-ADGroupMember -Identity $_ -Members $User -Confirm:$false
Might I add that you probably want to log every group membership you remove, just for the sake of easy recovery. Before removal, print the group DN's to a text file, identifying the user in question:
$LogFilePath = "C:\BackupLocation\user_" + $User.ObjectGUID.ToString() + ".txt"
Out-File $LogFilePath -InputObject $(User.memberOf) -Encoding utf8
This will write all the groups into the file and allow for easy and reliable rollback