Hey,
No limit to the UPN, just full first name. and last name.
And yes to your second question, simply add a digit until UPN is unique.
Import-Module Adaxes
$emailsuffix = "domain.co.uk"
$maximumLength = 10
$firstname = "%firstname%"
$surname = "%surname%"
function IsUserNameUnique($username)
{
$user = Get-AdmUser $username -erroraction silentlycontinue
return $user -eq $Null
}
# Get the username
$username = $Context.GetModifiedPropertyValue("samAccountName")
# Check user name Length
if ($username.Length -gt $maximumLength)
{
$username = $username.SubString(0 , $maximumLength)
}
elseif (IsUserNameUnique($username))
{
# Username is unique
return
}
# If the username is not unique, generate a unique one
$uniqueUsername = $username
for ($i = 1; $True; $i++)
{
if (IsUserNameUnique($uniqueUsername))
{
break
}
$difference = $maximumLength - $username.Length - $i.ToString().Length
if ($difference -lt 0)
{
$username = $username.Substring(0, $username.Length + $difference)
}
if ([System.String]::IsNullOrEmpty($username))
{
$Context.Cancel("Unable to generate a unique username, because the number length exceeds the maximum length of the username")
return
}
$uniqueUsername = $username + $i;
}
# Update User Logon Name (pre-Windows 2000)
$Context.SetModifiedPropertyValue("samAccountName", $uniqueUsername)
Function GetUserPrincipalname {
$result = "$($firstname).$($surname)@$($emailsuffix)"
$int = 2
$output = Get-ADUser -filter "UserPrincipalName -eq '$result'"
$tmpresult = $result
Do {
$output = Get-ADUser -filter "UserPrincipalName -eq '$tmpresult'"
if ($output -eq $Null) {
$result = $($tmpresult)
} else {
$result = "$($firstname).$($surname)$($int)@$($emailsuffix)"
$tmpresult = $($result)
$int = $int + 1
}
}
Until ($output -eq $Null)
Return $result
}
# Update User Logon Name
$userLogonName = GetUserPrincipalname
$Context.SetModifiedPropertyValue("userPrincipalName", $userLogonName)
$Context.LogMessage("The name has been changed to " + $objectName `
+ ".", "Information")