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

Check whether email and username are unique

June 29, 2023 Views: 3975

The script checks whether the email address and username specified for a new user are unique. If either the username or the email address are not unique, new user creation will be cancelled. To use the script with Adaxes, create a business rule triggered before creating a user. For details, see Validate/Modify User Input Using a Script.

Edit Remove
# Build criteria
if (-not([System.String]::IsNullOrEmpty("%mail%")))
    $expression = {sAMAccountName -eq "%username%" -or mail -eq "%mail%"}
    $expression = {sAMAccountName -eq "%username%"}
$criteria = New-AdmCriteria -Type "user" -Expression $expression

# Search for users with the username or email address specified
$searcher = $Context.BindToObject("Adaxes://rootDSE")
$searcher.Criteria = $criteria
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.VirtualRoot = $True
$searcher.SizeLimit = 1

    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    if ($searchResults.Length -ne 0)
        $Context.Cancel("A user with the same username or email address already exists")
    # Release resources
Comments 2
Ray Bilyk Apr 02, 2021
Is there a way to get an email if the new user creation is cancelled due to lack of uniqueness?
Support Apr 02, 2021
Hello Ray,

Yes, it is possible. You can use the $Context.SendMail method right after the following line in the script:

$Context.Cancel("A user with the same username or email address already exists")

Should you have any issues updating the script to meet your needs, please, describe the desired behavior in all the possible details with live examples.
Leave a comment

Got questions?

Support Questions & Answers