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: 966

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.
Edit Remove
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()
Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers