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

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
PowerShell
# Build criteria
if (-not([System.String]::IsNullOrEmpty("%mail%")))
{
    $expression = {sAMAccountName -eq "%username%" -or mail -eq "%mail%"}
}
else
{
    $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

try
{
    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    
    if ($searchResults.Length -ne 0)
    {
        $Context.Cancel("A user with the same username or email address already exists")
        return
    }
}
finally
{
    # Release resources
    $searchResultIterator.Dispose()
}
Comments 2
avatar
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?
avatar
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
Loading...

Got questions?

Support Questions & Answers