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 IDExample 2: 6 initial characters of the Last Name + 3 last characters of a string passed by $myTextPowerShell$samAccountName = BuildUsername ("%givenName%", 1, "Beginning") "%sn%" ` ("%employeeID%", 3, "End")
PowerShell$samAccountName = BuildUsername ("%sn%", 6, "Beginning") ` ($myText, 3, "End")
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.
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)
{
# Search parameters
$searcher = $Context.TargetObject
$searcher.Criteria = New-AdmCriteria "user" -Expression {sAMAccountName -eq $username}
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.SizeLimit = 1
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.VirtualRoot = $True
try
{
# Execute search
$searchResultIterator = $searcher.ExecuteSearch()
$searchResults = $searchResultIterator.FetchAll()
return $searchResults.Length -eq 0
}
finally
{
# Release resources
if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
}
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.")