The scripts can be used to automatically generate a unique username for a user by adding a digit. To use them with Adaxes, create a business rule triggered before creating a user that runs one of the scripts. For more details, see Validate/Modify User Input Using a Script.
Note: To use the scripts, you need to install Adaxes PowerShell Module on the computer, where your Adaxes service is running.
Username not limited by length
PowerShell
Import-Module Adaxes
function IsUserNameUnique($username)
{
$user = Get-AdmUser $username -erroraction silentlycontinue
return $user -eq $Null
}
# Get the username
$username = $Context.GetModifiedPropertyValue("samAccountName")
# Check if the username is unique
if (IsUserNameUnique($username))
{
return
}
# If the username is not unique, generate a unique one
$uniqueUsername = $Null
for ($i = 1; $True; $i++)
{
$uniqueUsername = $username + $i;
if (IsUserNameUnique($uniqueUsername))
{
break
}
}
# Update User Logon Name (pre-Windows 2000)
$Context.SetModifiedPropertyValue("samAccountName", $uniqueUsername)
# Update User Logon Name
$upnSuffix = $Context.GetObjectDomain("%distinguishedName%")
$userLogonName = $uniqueUsername + "@" + $upnSuffix
$Context.SetModifiedPropertyValue("userPrincipalName", $userLogonName)
$Context.LogMessage("The username was changed to " + $userLogonName `
+ ".", "Information")
Username has a length limitation
Parameter:
- $maximumLength - Specifies the maximum number of characters that a username can have.
PowerShell
Import-Module Adaxes
$maximumLength = 8 # TODO: modify me
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)
# Update User Logon Name
$upnSuffix = $Context.GetObjectDomain("%distinguishedName%")
$userLogonName = $uniqueUsername + "@" + $upnSuffix
$Context.SetModifiedPropertyValue("userPrincipalName", $userLogonName)
$Context.LogMessage("The username was changed to " + $userLogonName `
+ ".", "Information")