Hello,
Thank you for specifying. We adjusted the script from the repository article to meet your needs, please, find it below. It must be executed in a business rule triggering Before creating a user. The script generates values that start with the first letters of the first and last names of the created user and a sequential number. The script then updates the userPrincipalName and the sAMAccountName properties with the generated value. The last used number is then saved to the custom integer attribute of the domain whose distinguished name is specified in the $domainDN script variable.
$numberProperty = "adm-CustomAttributeInt1" # TODO: modify me
$domainDN = "DC=domain,DC=com" # TODO: modify me
$valueFormat = "%firstname,1%%lastname,1%{0:00000}" # TODO: modify me
$initialNumber = 10000 # TODO: modify me
$maxNumber = 19999 # TODO: modify me
function IsValueNotUnique($criteria)
{
$searcher = $Context.TargetObject
$searcher.Criteria = $criteria
$searcher.SizeLimit = 1
$searcher.VirtualRoot = $True
try
{
$searchResultIterator = $searcher.ExecuteSearch()
$searchResults = $searchResultIterator.FetchAll()
return $searchResults.Length -eq 1
}
finally
{
# Release resources
if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
}
# Get the number stored in domain property.
$domain = $Context.BindToObjectByDN($domainDN)
try
{
$number = [int]($domain.Get($numberProperty))
$number++
}
catch
{
# Use the initial number
$number = $initialNumber
}
# Build value
$uniqueValue = [System.String]::Format($valueFormat, $number)
do
{
if ($number -gt [int]$maxNumber)
{
$Context.Cancel("Cannot generate a new value for $propertyName because the maximum `
allowed object number has been reached. Contact your system administrator.")
return
}
$upn = $Context.GetModifiedPropertyValue("userPrincipalName")
$newUpn = $uniqueValue + $upn.SubString($upn.IndexOf("@"))
$criteria = New-AdmCriteria -Type "User" -Expression {(userPrincipalName -eq $newUpn) -or (sAMAccountName -eq $uniqueValue)}
$isValueNotUnique = IsValueNotUnique $criteria
if ($isValueNotUnique)
{
# If the value is already in use, generate a unique one.
$number++
$uniqueValue = [System.String]::Format($valueFormat, $number)
}
}
while ($isValueNotUnique)
# Update the number in doamin property
$domain.Put($numberProperty, $number)
$domain.SetInfo()
# Update property values.
$Context.SetModifiedPropertyValue("sAMAccountName", $uniqueValue)
$Context.SetModifiedPropertyValue("userPrincipalName", $newUpn)