Forum Discussion

Matt_P_Standing's avatar
Matt_P_Standing
Brass Contributor
Jun 04, 2024
Solved

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:   ...
  • Harm_Veenstra's avatar
    Jun 04, 2024

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

Resources