SOLVED

Remove groups from a user with an exception

Brass Contributor

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

4 Replies
best response confirmed by Matt_P_Standing (Brass Contributor)
Solution

@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
        }
    }
}
Did that work out for you?

@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 :)
1 best response

Accepted Solutions
best response confirmed by Matt_P_Standing (Brass Contributor)
Solution

@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
        }
    }
}

View solution in original post