Active Directory remove user from GroupA if member of GroupB

active-directorygroupsuser-management

In Active Directory, how do I efficiently remove all users from GroupA who are members of GroupB? Basically I want to subtract B from A.

Have now:

AAA         BBB
---         ---
Alice       Alice
Charlene    Bruce
Chuck       Chuck

Desired:

AAA         BBB
---         ---
            Alice
Charlene    Bruce
            Chuck

I have the user lists in csv at the moment but can reorganize quickly to something else if needed:

logon, group
alice, AAA
alice, BBB
bruce, BBB
...

I'm not an AD admin, just a user who has write privileges for these groups.

Best Answer

Powershell Active Directory Web Services. Comes with all Domain Controllers 2008 R2 or better by default.

# This foreach loop enumerates through all members of the AAA group.
Foreach ($Usr In Get-ADGroupMember -Identity 'CN=AAA,CN=Users,DC=Contoso,DC=com')
{
    # If the 'MemberOf' array of $Usr's group memberships contains 'BBB', then...
    If ((Get-ADUser $Usr.SamAccountName -Properties MemberOf).MemberOf -Contains 'CN=BBB,CN=Users,DC=contoso,DC=com')
    {
        # Remove that user from 'AAA'.
        Remove-ADGroupMember -Identity 'AAA' -Members $Usr.SamAccountName
    }
}

That will remove all members of group 'AAA' who are also members of group 'BBB'. No CSV needed.

If you are using less than Powershell 3, use Import-Module ActiveDirectory before you start using AD cmdlets.