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: AD, AD cmdlets, Active Directory, Examples, PowerShell, cmdlets
Thanks, Dmitry. The Quest AD CmdLets continue to be awesome!
Nice!