The script generates a unique 6-digit value for the specified Active Directory property. To run the script, create a custom command, business rule or scheduled task configured for the User object type.
Parameters
- $propertyName - Specifies the LDAP name of the AD property that stores the 6-digit values and where the new unique value will be saved for the user.
- $maxNumber - Specified the maximum allowed property value.
PowerShell
$propertyName = "pager" # TODO: modify me
$maxNumber = 999999 # TODO: modify me
# Get all existing values
$searcher = $Context.BindToObject("Adaxes://rootDSE")
$searcher.SearchFilter = "(&(sAMAccountType=805306368)($propertyName=*))"
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.VirtualRoot = $True
try
{
$searchResultIterator = $searcher.ExecuteSearch()
$searchResults = $searchResultIterator.FetchAll()
}
finally
{
# Release resources
if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
$valuesFromAD = New-Object "System.Collections.Generic.HashSet[System.String]"
foreach ($searchResult in $searchResults)
{
[void]$valuesFromAD.Add($searchResult.Properties[$propertyName].Value)
}
# Generate new value
$usedValues = New-Object "System.Collections.Generic.HashSet[System.String]"
do
{
$number = Get-Random -Minimum 0 -Maximum $maxNumber
$uniqueValue = [System.String]::Format("{0:000000}", $number)
[void]$usedValues.Add($uniqueValue)
if ($usedValues.Count -eq $maxNumber)
{
$Context.LogMessage("All possible values are already in use.", "Warning")
return
}
}
while ( $valuesFromAD.Contains($uniqueValue))
# Update user
$Context.TargetObject.Put($propertyName, $uniqueValue)
$Context.TargetObject.SetInfo()