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

Update group membership with business unit members

August 14, 2023 Views: 1344

The script updates group membership with members of a business unit. All other members will be removed from the group. To run the script, create a business rule, custom command or scheduled task configured for the Group object type.

In the script, the $businessUnitName variable specifies the name of the business unit, whose members will be added to the group.

Edit Remove
PowerShell
$businessUnitName = "My unit" # TODO: modify me

# Search the business unit
$businessUnitsPath = $Context.GetWellKnownContainerPath("BusinessUnits")
$searcher = $Context.BindToObject($businessUnitsPath)
$searcher.Criteria = New-AdmCriteria "adm-BusinessUnit" -Expression {name -eq $businessUnitName}
$searcher.SizeLimit = 1

try
{
    # Execute search
    $searchResultIterator = $searcher.ExecuteSearch()
    $unitSearchResults = $searchResultIterator.FetchAll()
}
finally
{
    # Release resources
    if ($searchResultIterator){ $searchResultIterator.Dispose() }
}

if ($unitSearchResults.Length -gt 1)
{
    $Context.LogMessage("Found more than one business unit with name '$businessUnitName'.", "Warning")
    return
}
if ($unitSearchResults.Length -eq 0)
{
    $Context.LogMessage("Business unit '$businessUnitName' does not exist.", "Error")
    return
}

# Get member DNs
$unit = $Context.BindToObject($unitSearchResults[0].AdsPath)
$membershipRules = $unit.GetMembershipRules()
$memberGuids = $unit.GetMemberGuids($membershipRules)
$memberSearcher = $Context.CreateGuidBasedSearcher($memberGuids)

try
{
    # Execute search
    $searchResultIterator = $memberSearcher.ExecuteSearch()
    $memberSearchResults = $searchResultIterator.FetchAll()
}
finally
{
    # Release resources
    if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
$memberDNs = New-Object "System.Collections.ArrayList"
$memberSearchResults | %%{[void]$memberDNs.Add($_.Properties["distinguishedName"].Value)}

# Update group membership
$Context.TargetObject.Put("member", $memberDNs.ToArray())
$Context.TargetObject.SetInfo()

Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers