Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 "user1@domain.com"}

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.

share|improve this question
    
So you're starting with a user, and wanting to remove its membership in all groups? –  Tim Ferrill Jun 4 at 16:19

1 Answer 1

up vote 7 down vote accepted

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

share|improve this answer
    
the last operation (Go through the groups and remove the user) waits for more parameters (gives a >> output..) why? –  NirPes Jun 4 at 16:34
    
never mind, it was the brackets... thanks! –  NirPes Jun 4 at 16:36
    
Yes, fixed the last ending bracket and added a few suggestions. You're most welcome –  Mathias R. Jessen Jun 4 at 16:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.