Script Repository


Add users to group in bulk

August 18, 2016
1244

The script adds users to an AD group in bulk. Users are identified by their usernames specified in a certain property of the group.

To use the script, you can create a Business Rule triggered after creating or modifying an AD group. Sample Business Rule:

Parameter:

  • $propertyForUsernames - specifies the LDAP name of the property that will be used to specify the users to add to the groups. The value of the property must specify a comma-separated list of usernames of the user accounts that will be added to the group.
Edit Remove
PowerShell
Import-Module Adaxes

$propertyForUsernames = "adm-CustomAttributeText1" #TODO: modify me

# Get list of usernames from the virtual property
try
{
    $sAMAccountNames = ($Context.TargetObject.Get($propertyForUsernames)).Split(",")
}
catch
{
    return
}

# Get the current members of the group
try
{
    $memberGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMembersGuid")
}
catch
{
    $memberGuidsBytes = @()
}

$memberGuids = New-Object "System.Collections.Generic.HashSet[System.Guid]"
$memberGuidsBytes | %%{ $memberGuids.Add([Guid]$_) }

$domainName = $Context.GetObjectDomain("%distinguishedName%")
foreach ($sAMAccountName in $sAMAccountNames)
{
    try
    {
        $user = Get-AdmUser $sAMAccountName -Server $domainName -AdaxesService localhost -ErrorAction Stop
    }
    catch
    {
        # The user was not found
        $Context.LogMessage("User $sAMAccountName was not found", "Warning") # TODO: modify me
        continue
    }
    
    # Add the user to the group if the user is not yet a member
    $userGuid = [Guid]$user.ObjectGUID
    if (-not($memberGuids.Contains($userGuid)))
    {
        $Context.TargetObject.Add("Adaxes://<GUID=$userGuid>")
    }
    else
    {
        $Context.LogMessage("User $sAMAccountName is already a member of the group.", "Information") # TODO: modify me
    }
}

# Clear virtual attribute
$Context.TargetObject.Put($propertyForUsernames, $NULL)
$Context.TargetObject.SetInfo()

Comments ( 0 )
No results found.
Leave a comment

Related Scripts