Script repository

Check whether email and username are unique

Updated on: Jan 18, 2026, Views: 7553

Property validation

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, user creation will be cancelled. To execute the script, create a business rule triggering Before creating a user.

# 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 parameters
$searcher = $Context.TargetObject
$searcher.Criteria = $criteria
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.VirtualRoot = $True
$searcher.SizeLimit = 1

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

You must be signed in to comment.

  • Ray Bilyk

    Ray Bilyk

    Is there a way to get an email if the new user creation is cancelled due to lack of uniqueness?

    • Support

      Support

      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.

  • Baul

    Baul

    Hello

    Is there a way to modify the username from the already existing one to another username for the new user?

    Like this: Already existing username ("pak") > new user ("pki")

  • Support

    Support

    Hello,

    Yes, it is possible. For details and examples, have a look at the following tutorial: https://www.adaxes.com/help/ValidateModifyUserInputWithScript.

    • Baul

      Baul

      Thank you, i will try if it works.

  • Mark Monaco

    Mark Monaco

    Is there a way to modify this script so that it checks if a name and email address already exist for a group (either a mail-enabled security group or a distribution list)?

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.