We are currently using the script below to check for a unique username/upn. If the name is not unique, it adds a number to the end. In the Adaxes logs, everything appears to be working just fine. When the script finds a duplicate name, it adds the unique number as expected. The issue is with the email address. We use the upn to create the email address. (hybrid exchange environment) For some reason, the email address gets created with one number higher than expected. Example: Script runs, assigns the upn testuser1 because testuser exist. The email address gets created as testuser2@domain.com. Any idea as to why this would happen?
$maximumLength = 8 # TODO: modify me
$upnPrefix = "%firstname%%lastname%" # TODO: modify me
function IsUserValueUnique($filter)
{
$user = Get-AdmUser -LdapFilter $filter -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)
}
#User Logon Name (pre-Windows 2000)
$uniqueUsername = $username
for ($i = 1; $True; $i++)
{
if (IsUserValueUnique "(sAMAccountName=$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;
}
#User Logon Name
$upnSuffix = "franklincountyohio.gov"
$uniqueUPN = "$upnPrefix@$upnSuffix"
for ($i = 1; $True; $i++)
{
if (IsUserValueUnique "(userPrincipalName=$uniqueUPN)")
{
break
}
$uniqueUPN = "$upnPrefix$i@$upnSuffix"
}
#Update User Logon Name (pre-Windows 2000)
$Context.SetModifiedPropertyValue("samAccountName", $uniqueUsername)
#Update User Logon Name
$Context.SetModifiedPropertyValue("userPrincipalName", $uniqueUPN)
$Context.LogMessage("The username has been changed to " + $uniqueUPN `
+ ".", "Information")