Script repository

Add object to the group with the least number of members

Updated on: Jan 18, 2026, Views: 6389

Group membership

The script adds the target object to the group with the least number of members from the list of predefined groups. To execute the script, create a business rule, custom command or scheduled task configured for the required object type.

In the script, the $groupDNs variable specifies the distinguished names (DNs) of the groups from which the one with the least number of users will be selected to add the target object. For information on how to get an object DN, see Get the DN of a directory object.

$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
$groupWithMinMembers = $NULL
foreach ($dn in $groupDNs)
{
    $group = $Context.BindToObjectByDN($dn)
    try
    {
        $memberGuidsBytes = $group.GetEx("adm-DirectMembersGuid")
    }
    catch
    {
        $memberGuidsBytes = @()
    }

    if ($NULL -eq $membersCount)
    {
        $membersCount = $memberGuidsBytes.Length
        $groupWithMinMembers = $group
    }
    elseif ($membersCount -gt $memberGuidsBytes.Length)
    {
        $membersCount = $memberGuidsBytes.Length
        $groupWithMinMembers = $group
    }
}

# Add user to the group.
$groupWithMinMembers.Add($Context.TargetObject.AdsPath)

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.