Script repository

Generate a unique 6-digit value for AD property

Updated on: Jan 18, 2026, Views: 1687

Provisioning

The script generates a unique 6-digit value for the specified property. To execute the script, create a business rule, custom command or scheduled task configured for the required object type.

Parameters

  • $propertyName - the name of the property to generate a unique 6-digit value for.
  • $maxNumber - the maximum allowed property value.
$propertyName = "pager" # TODO: modify me
$maxNumber = 999999 # TODO: modify me

# Build criteria
$criteria = New-AdmCriteria "user"

$simpleItem = $criteria.CreateSimple()
$simpleItem.SetProperty($propertyName).SetComparisonOperator("empty").AddValue($False)
$criteria["user"].Add($simpleItem)

# Search parameters
$searcher = $Context.TargetObject
$searcher.Criteria = $criteria
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.VirtualRoot = $True

try
{
    # Execute search
    $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()

Comments 0

You must be signed in to comment.

    Got questions?

    Support Questions & Answers

    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.