The script adds the target object to the group with the least number of members from the list of predefined groups. The script can be executed in a custom command, business rule or scheduled task.
In the script, the $groupDNs variable specifies the distinguished names (DNs) of the groups from which the one with the least number of users wil be selected to add the target object. For information on how to get an object DN, see Get the DN of a directory object.
PowerShell
$groupDNs = @(
"CN=MyGroup1,OU=Groups,DC=domain,DC=com",
"CN=MyGroup2,OU=Groups,DC=domain,DC=com"
) # TODO: modify me
# Get group with minimum members
$membersCount = $NULL
$groupWtihMinMembers = $NULL
foreach ($dn in $groupDNs)
{
$group = $Context.BindToObjectByDN($dn)
try
{
$memberGuidsBytes = $group.GetEx("adm-DirectMembersGuid")
}
catch
{
$memberGuidsBytes = @()
}
if ($NULL -eq $membersCount)
{
$membersCount = $memberGuidsBytes.Length
$groupWtihMinMembers = $group
}
elseif ($membersCount -gt $memberGuidsBytes.Length)
{
$membersCount = $memberGuidsBytes.Length
$groupWtihMinMembers = $group
}
}
# Add user to the group
$groupWtihMinMembers.Add($Context.TargetObject.AdsPath)