Keep group membership under control

How do you keep group membership in your AD automatically adhere to the right lists of members (whatever “right” means in your case)? We had an interesting thread on that in the AD discussion forum and below the script which came out of it.

Basically, in Matthew’s case he is getting text files for each group listing the members which should be there (I am guessing some HR DB exports). He obviously cannot just remove everyone and recreate membership from scratch – because this can affect users (imagine if this is a DL and en email is being sent when you do this) and cause additional stress on AD. Instead, he needs to detect which users should be taken out and remove them from the group, and detect the ones which he needs to add and add them.

It turns out that with PowerShell this basically comes down to a single command (Compare-Object) comparing the file and the actual output, and an If performing the corresponding action (add or remove) based on the direction.

I am using samAccountName but you could use DN or another unique identifier. One thing to keep in mind is the -SyncWindow parameter of Compare-Object. By default it is 5. You may need to make it bigger depending on your group size.

Apart from that, everything is very straight-forward (you can obviously wrap the code into a function and use it for multiple groups):

# name of the group to update
$groupname = "Managers"
# import a file: one samAccountName per line
$users = get-Content c:\user_logon_names.txt
# get samAccountNames of current members into an array
$members = @()
Get-QADGroupMember $groupname | ForEach-Object { $members += $_.samAccountName }

# make group membership exactly as it is in the file
Compare-Object $users $members | ForEach-Object {
    If ( $_.SideIndicator -eq '<=' ) {
        "Adding $($_.InputObject) to $groupname"
        Get-QADUser $_.InputObject | Add-QADGroupMember $groupname
    } elseif ( $_.SideIndicator -eq '=>'  ) {
        "Removing $($_.InputObject) from $groupname"
        Get-QADUser $_.InputObject | Remove-QADGroupMember $groupname
    }
}

The script uses Quest AD cmdlets, so you would need to have them installed and loaded either explicitly in the script (with Add-PSSnapin) or in your PowerShell profile.

Tags: , , , , ,

2 Responses to “Keep group membership under control”


  1. 1 matthew April 23, 2008 at 3:43 am

    Thanks, Dmitry. The Quest AD CmdLets continue to be awesome!


Leave a comment




Legal

The posts on this blog are provided “as is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer - WSO2 or anyone else for that matter. All trademarks acknowledged.

© 2007-2014 Dmitry Sotnikov

April 2008
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930