Home > Software design >  How to make my PSS to remove a user all group membership with an exception (Keeping 1 group)?
How to make my PSS to remove a user all group membership with an exception (Keeping 1 group)?

Time:10-12

I am not an expert in PowerShell, but this is what I am trying to accomplish: I have a PowerShell script that lists all users in a particular OU and then checks if they have any group membership affiliation, after that it should remove all those memberships but keep 1 specific group if it exists in their memberships, however, I am running the script but it is doing nothing at all, no error messages received and no removing the other group memberships. Will appreciate it if could help me find out what I am missing.

This is an example of my code:

    import-Module activedirectory
    $DisabledUsers = Get-ADUser -Filter { enabled -eq $false }  -Properties memberof -SearchBase "OU=Test Users,OU=Users,OU=Site2,OU=Site,DC=fqm,DC=test"
    Foreach ($user in $DisabledUsers) {
        $Groups = $User.memberof
        $Mcast = Get-ADGroup -identity Disable_test_group
        $Muser = (Get-ADUser $user -Properties mail)
    
        Foreach ($GN in $Groups) {
    
            if ($GN -ne $Mcast) {
                Get-ADGroup $GN | Remove-ADGroupMember -Confirm:$false -Members $User.samaccountname 
            }
        }
    }

CodePudding user response:

You're over complicating it, first it would be better to use Remove-ADPrincipalGroupMembership in this case. Then you're querying the Disable_test_group group per loop iteration when you only need to query it once.

# base OU
$base = "OU=Test Users,OU=Users,OU=Site2,OU=Site,DC=fqm,DC=test"

# get the DN of the group that needs to be excluded
$exclude = (Get-ADGroup -Identity Disable_test_group).DistinguishedName

# get all disabled users
Get-ADUser -Filter "enabled -eq '$false'" -Properties memberof -SearchBase $base |
    # for each disabled user
    ForEach-Object {
        # exclude the group from the `MemberOf` array
        $toRemove = $_.MemberOf -ne $exclude
        # if there are no groups to remove, go next user
        if(-not $toRemove) { return }
        # if there are, remove this user as a member of
        $_ | Remove-ADPrincipalGroupMembership -MemberOf $toRemove
    }
  • Related