Script Repository


Create username automatically

December 29, 2017
2075

The below PowerShell function can be used to create a username for a new user automatically based on values of the user properties. For example, you can use it to create a username consisting of portions of the First Name, Last Name and include the Employee ID.

To use it in your environment, configure a Business Rule triggered before creating a new user that runs your PowerShell script. For more information, see Validate/Modify User Input Using a Script.

Example Usage:

Example 1: 1st character of the First Name + complete Last Name + 3 last characters of the Employee ID
Edit Remove
PowerShell
$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
Edit Remove
PowerShell
$samAccountName = BuildUsername ("%sn%", 6, "Beginning") `
                  ($myText, 3, "End")
Edit Remove
PowerShell
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()
}

Sample Script

In the following script, the function is used to create a unique username for a user. If the script manages to create a unique username, it assigns it to the user, otherwise it cancels new user creation with an error message.

Edit Remove
PowerShell
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()
}

Import-Module Adaxes

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)
    
    # Inform the user
    $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 the username
$username = $Context.GetModifiedPropertyValue("samAccountName")

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

# Try building a unique username automatically

# 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))
{
    # The username is unique. Update username and exit script
    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))
{
    # The username is unique. Update username and exit script
    SetUsername($uniqueUsername)
    return
}

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


Comments ( 0 )
No results found.
Leave a comment