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.

Script repository

Adjust group membership based on mapping

March 15, 2021 Views: 1248

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
PowerShell
$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"
    
    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
Leave a comment
Loading...

Got questions?

Support Questions & Answers