Script repository

Adjust group membership based on mapping

Updated on: Jan 18, 2026, Views: 2310

Group membership

The script adds/removes user from groups based on the predefined mapping. To execute the script, create a scheduled task configured for the Domain object type and add a managed domain to the Activity Scope of the task. The domain will only be used to trigger execution of the scheduled task.

In the script, the $groupMap variable maps distinguished names (DNs) of the groups users must be members of. If a user is a member of the first group in the mapping, but is not a member of the second group, they will be added to the group. If a user is not a member of the first group, but is a member of the second group, they will be removed from the group. For information on how to get an object DN, see Get the DN of a directory object.

$groupMap = @{
    "CN=Group1,OU=Groups,DC=Example,DC=com" = "CN=Group2,OU=Groups,DC=Example,DC=com";
    "CN=Group3,OU=Groups,DC=Example,DC=com" = "CN=Group4,OU=Groups,DC=Example,DC=com"
} # TODO: modify me

foreach ($dn in $groupMap.Keys)
{
    # Search parameters
    $firstGroup = $Context.BindToObjectByDN($dn)
    $firstGroup.Criteria = New-AdmCriteria "*"
    $firstGroup.SearchScope = "ADS_SCOPE_BASE"
    $firstGroup.PageSize = 500
    $firstGroup.AttributeScopeQuery = "member"
    
    try
    {
        # Execute search
        $searchIterator = $firstGroup.ExecuteSearch()
        $searchResults = $searchIterator.FetchAll()
    }
    finally
    {
        # Release resources
        if ($searchIterator){ $searchIterator.Dispose() }
    }
    
    $secondGroup = $Context.BindToObjectByDN($groupMap[$dn])
    if ($searchResults.Length -eq 0)
    {
        $secondGroup.Put("member", $NULL)
    }
    else
    {
        # Get member DNs.
        $memberDNs = $searchResults | %%{$_.Properties["distinguishedName"].Value}
        
        # Update second group.
        $secondGroup.Put("member", $memberDNs)
        $secondGroup.SetInfo()
    }
    
    # Save the changes
    $secondGroup.SetInfo()
}

Comments 0

You must be signed in to comment.

    Got questions?

    Support Questions & Answers

    We use cookies to improve your experience.
    By your continued use of this site you accept such use.
    For more details please see our privacy policy and cookies policy.