Script repository

Generate unique username

Updated on: Jan 18, 2026, Views: 12669

Property validation

This PowerShell function can be used to generate a username for a new user based on values of their properties. To use it in your workflows, create a business rule triggering Before creating a new user.

function BuildUsername()
{
    $samAccountNameBuilder = New-Object "System.Text.StringBuilder"
    for ($i=0; $i -lt $args.length; $i++)
    {
        if (-not($args[$i] -is [array]))
        {
            if (-not([System.String]::IsNullOrEmpty($args[$i])))
            {
                [void]$samAccountNameBuilder.Append($args[$i].ToLower())
            }
        }
        elseif ($args[$i].length -eq 3) 
        {
            if (-not([System.String]::IsNullOrEmpty($args[$i][0])))
            {
                $valueLength = $args[$i][1]
                if ($valueLength -gt $args[$i][0].Length)
                {
                    $valueLength = $args[$i][0].Length
                }
                
                switch ($Args[$i][2])
                {
                    "Beginning"
                    {
                        $value = $args[$i][0].SubString(0,$valueLength).ToLower()
                    }
                    "End"
                    {
                        $value = $args[$i][0].SubString($args[$i][0].Length - $valueLength).ToLower()
                    }
                }
                [void]$samAccountNameBuilder.Append($value)
            }
        }
        else
        {
            $Context.LogMessage("An error occurred while building a username!", "Error")
        }
    }

    return $samAccountNameBuilder.ToString()
}

Example 1: First character of the First Name + complete Last Name + 3 last characters of the Employee ID

$samAccountName = BuildUsername ("%givenName%", 1, "Beginning") "%sn%" `
                  ("%employeeID%", 3, "End")

Example 2: 6 initial characters of the Last Name + 3 last characters of a string passed by $myText

$samAccountName = BuildUsername ("%sn%", 6, "Beginning") `
                  ($myText, 3, "End")

Full sample script

In the following script, the function is used to generate a unique username for a user. If there is no possibility to generate a unique username, the script cancels user creation with the corresponding message.

function BuildUsername()
{
    $samAccountNameBuilder = New-Object "System.Text.StringBuilder"
    for ($i=0; $i -lt $args.length; $i++)
    {
        if (-not($args[$i] -is [array]))
        {
            if (-not([System.String]::IsNullOrEmpty($args[$i])))
            {
                [void]$samAccountNameBuilder.Append($args[$i].ToLower())
            }
        }
        elseif ($args[$i].length -eq 3) 
        {
            if (-not([System.String]::IsNullOrEmpty($args[$i][0])))
            {
                $valueLength = $args[$i][1]
                if ($valueLength -gt $args[$i][0].Length)
                {
                    $valueLength = $args[$i][0].Length
                }
                
                switch ($Args[$i][2])
                {
                    "Beginning"
                    {
                        $value = $args[$i][0].SubString(0,$valueLength).ToLower()
                    }
                    "End"
                    {
                        $value = $args[$i][0].SubString($args[$i][0].Length - $valueLength).ToLower()
                    }
                }
                [void]$samAccountNameBuilder.Append($value)
            }
        }
        else
        {
            $Context.LogMessage("An error occurred while building a username!", "Error")
        }
    }

    return $samAccountNameBuilder.ToString()
}

function IsUserNameUnique($username)
{
    $user = Get-AdmUser $username -erroraction silentlycontinue
    return $user -eq $Null
}

function SetUsername($samAccountName)
{
    # Update samAccountName
    $Context.SetModifiedPropertyValue("samAccountName", $samAccountName)

    # Update userPrincipalName
    $userPrincipalName = $samAccountName + "@" + `
        $Context.GetObjectDomain("%distinguishedName%")

    $Context.SetModifiedPropertyValue("userPrincipalName", $userPrincipalName)
    
    # Output data
    $Context.LogMessage("User Logon Name (pre-Windows 2000) has been changed to: $samAccountName", "Information")
    $Context.LogMessage("User Logon Name has been changed to: $userPrincipalName", "Information")
}

# Get samAccountName
$username = $Context.GetModifiedPropertyValue("samAccountName")

# Check whether the username is already unique.
if (IsUserNameUnique $username)
{
    return
}

# Use 3 initial characters of the First Name and Last Name.
$uniqueUsername = BuildUsername ("%givenName%", 3, "Beginning") ("%sn%", 3, "Beginning")

# Check whether the username is unique.
if (IsUserNameUnique $uniqueUsername)
{
    SetUsername $uniqueUsername
    return
}

# Use 2 initial characters of the First Name and 4 initial characters of the Last Name.
$uniqueUsername = BuildUsername ("%givenName%", 2, "Beginning") ("%sn%", 4, "Beginning")

# Check whether the username is unique.
if (IsUserNameUnique $uniqueUsername)
{
    SetUsername $uniqueUsername
    return
}

# Failed to generate a unique username. Cancel user creation.
$Context.Cancel("Failed to generate a unique username. You need to input a unique username manually.")

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.