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.

Script Repository

Generate a unique 6-digit value for AD property

February 25, 2021 Views: 961

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.


  • $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.
Edit Remove
$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

    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    # Release resources
    if ($searchResultIterator){ $searchResultIterator.Dispose() }

$valuesFromAD = New-Object "System.Collections.Generic.HashSet[System.String]"
foreach ($searchResult in $searchResults)

# Generate new value
$usedValues = New-Object "System.Collections.Generic.HashSet[System.String]"
    $number = Get-Random -Minimum 0 -Maximum $maxNumber
    $uniqueValue = [System.String]::Format("{0:000000}", $number)
    if ($usedValues.Count -eq $maxNumber)
        $Context.LogMessage("All possible values are already in use.", "Warning")
while ( $valuesFromAD.Contains($uniqueValue))

# Update user
$Context.TargetObject.Put($propertyName, $uniqueValue)
Comments 0
Leave a comment

Got questions?

Support Questions & Answers