The script adds users to an AD group in bulk. Users are identified by their sAMAccountNames specified in a custom attribute of the group. To execute the script, you can create a business rule triggered After creating a group or After updating a group.
Parameter:
- $propertyForUsernames - Specifies the LDAP name of the property that will be used to specify sAMAccountNames the users to add to the group. sAMAccountNames in the property must be separated by commas (e.g. user1,user2,user3).
PowerShell
$propertyForUsernames = "adm-CustomAttributeText1" #TODO: modify me
function SearchObjects($filter)
{
$searcher = $Context.TargetObject
$searcher.SearchFilter = $filter
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.SizeLimit = 2
$searcher.VirtualRoot = $True
try
{
# Execute search
$searchResultIterator = $searcher.ExecuteSearch()
$searchResults = $searchResultIterator.FetchAll()
return ,$searchResults
}
finally
{
# Release resources
if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
}
# Get usernames from the custom attribute
try
{
$sAMAccountNames = ($Context.TargetObject.Get($propertyForUsernames)).Split(",")
}
catch
{
return
}
# Get the current group members
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)
{
$searchResults = SearchObjects "(sAMAccountName=$sAMAccountName)"
if ($searchResults.Length -eq 0)
{
$Context.LogMessage("Account with username $sAMAccountName not found.", "Warning")
continue
}
elseif ($searchResults.Length -gt 1)
{
$Context.LogMessage("Found more than one account with username $sAMAccountName", "Warning")
continue
}
# Add the user to the group
$userGuid = [Guid]$searchResults[0].Properties["objectGUID"].Value
if (-not($memberGuids.Contains($userGuid)))
{
try
{
$Context.TargetObject.Add("Adaxes://<GUID=$userGuid>")
}
catch
{
$Context.LogMessage("An error occurred when addingaccount with username $sAMAccountName to the group. Error: " + $_.Exception.Message, "Warning") # TODO: modify me
}
}
else
{
$Context.LogMessage("User $sAMAccountName is already a member of the group.", "Information") # TODO: modify me
}
}
# Clear custom attribute
$Context.TargetObject.Put($propertyForUsernames, $NULL)
$Context.TargetObject.SetInfoEx(@($propertyForUsernames))