Script Repository

Adjust group membership based on mapping

March 15, 2021

The script adds/removes user from groups based on the predefined mapping. To execute the script, create a scheduled task configured for the Domain-DNS object type and assign it over a managed domain.

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.

Edit Remove
$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.SearchFilter = "(objectClass=*)"
    $firstGroup.SearchScope = "ADS_SCOPE_BASE"
    $firstGroup.PageSize = 500
    $firstGroup.AttributeScopeQuery = "member"
        # Execute search
        $searchIterator = $firstGroup.ExecuteSearch()
        $searchResults = $searchIterator.FetchAll()
        # Release resources
        if ($searchIterator){ $searchIterator.Dispose() }
    $secondGroup = $Context.BindToObjectByDN($groupMap[$dn])
    if ($searchResults.Length -eq 0)
        $secondGroup.Put("member", $NULL)
        # Get member DNs
        $memberDNs = $searchResults | %%{$_.Properties["distinguishedName"].Value}
        # Update second group
        $secondGroup.Put("member", $memberDNs)
    # Save the changes

Comments ( 0 )
No results found.
Leave a comment

Related Scripts