Script Repository


Update AD group membership of a user based on business unit membership

February 25, 2021
433

The script adds/remove users from Active Directory groups based on the business units the users are members of. To run the script, create a scheduled task configured for the Domain-DNS object type and add a managed domain to the Activity Scope of the task.

Parameter:

  • $unitDNsToGroupDNs - Maps distinguished names (DNs) of the business units a user needs to be a member of to be added Active Directory groups with DNs of the groups that correspond to each business unit. A business unit can have one or more associated group. For information on how to get DN of a directory object, see Get the DN of a directory object.
Edit Remove
PowerShell
$unitDNsToGroupDNs = @{
    "CN=My Unit1,CN=Business Units,CN=Configuration Objects,CN=Adaxes Configuration,CN=Adaxes" = @(
        "CN=MyGroup1,OU=Groups,DC=domain,DC=com", 
        "CN=MyGroup2,OU=Groups,DC=domain,DC=com");
    "CN=My Unit2,CN=Business Units,CN=Configuration Objects,CN=Adaxes Configuration,CN=Adaxes" = @(
        "CN=MyGroup3,OU=Groups,DC=domain,DC=com");
} # TODO: modify me

foreach ($unitDN in $unitDNsToGroupDNs.Keys)
{
    # Get member DNs
    $unit = $Context.BindToObjectByDN($unitDN)
    $membershipRules = $unit.GetMembershipRules()
    $memberGuids = $unit.GetMemberGuids($membershipRules)
    $memberSearcher = $Context.CreateGuidBasedSearcher($memberGuids)
    
    try
    {
        $searchResultIterator = $memberSearcher.ExecuteSearch()
        $memberSearchResults = $searchResultIterator.FetchAll()
    }
    finally
    {
        # Release resources
        if ($searchResultIterator){ $searchResultIterator.Dispose() }
    }
    
    # Get object DNs
    $memberDNs = New-Object "System.Collections.ArrayList"
    $memberSearchResults | %%{[void]$memberDNs.Add($_.Properties["distinguishedName"].Value)}
    
    foreach ($dn in $unitDNsToGroupDNs[$unitDN])
    {
        $group = $Context.BindToObjectByDN($dn)
        
        # Update group membership
        $group.Put("member", $memberDNs.ToArray())
        $group.SetInfo()
    }
}

Comments ( 0 )
No results found.
Leave a comment

Related Scripts