Shadow Groups…

… or “Why can’t I apply group membership based on OU?”

You will occasionally find that rather than manage your groups you’d really like to just have users automatically be a member of specific groups based on what OU they’re in. Kind of like Dynamic DL’s in Exchange.

There’s no inherent way to do this in AD. Shocker, I know. But it’s fairly easy to do in Powershell. Then all you have to do is create a task to execute your script every 15 minutes or whatever interval you like.

Here’s the basics of the script.  Essentially it queries the OU you specify and pulls all the users in that OU into an array. Then it pulls a list of users who are in the group already. Then it just does  a compare on the 2 lists to ensure that the members of the group match the users in the OU. It adds/removes as necessary.


import-module ActiveDirectory

function AddToGroup {
param ($Group,$OU)

$users = $(get-aduser -SearchBase $OU -filter "*")
if (!$users){$users=$(get-aduser "Guest")}

$groupmembers = Get-ADGroupMember -Identity $Group
if (!$groupmembers){add-adgroupmember -identity $group -member "guest"}

switch (Compare-Object -ReferenceObject $groupmembers -DifferenceObject $users -property distinguishedname)
 {
 {$_.SideIndicator -eq "=>"} {add-adgroupmember -identity $group -member $_.distinguishedname}
 {$_.SideIndicator -eq "<="} {remove-adgroupmember -identity $group -member $_.distinguishedname -confirm:$false}
 }

}

You then have the option of either calling it inline or as part of the script itself. I choose to just run it and manage the groups in the script itself:


AddToGroup "G_FGrained_AA" "OU=AO,OU=specialized Accounts,DC=mydomain,DC=com"
AddToGroup "G_FGrained_BA" "OU=BA,OU=specialized Accounts,DC=mydomain,DC=com"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s