I create an account in another ou, where there are no duplicates, but still an error. I tried to check for duplicates in one OU, also an error!
Screenshot 2022-11-21 112625.png
Script:
Import-Module Adaxes
function IsUserNameUnique($username)
{
$domain = $Context.GetObjectDomain("%distinguishedName%")
$user = Get-AdmUser -Filter {userPrincipalName -eq $username} -Server $domain -AdaxesService localhost
return $null -eq $user
}
$username = $Context.GetModifiedPropertyValue("userPrincipalName")
$firstname = $Context.GetModifiedPropertyValue("givenName")
$lastname = $Context.GetModifiedPropertyValue("sn")
if (IsUserNameUnique($username))
{
return
}
$localPart, $domainPart = $username.Split("@")
$uniqueUsername = $Null
for ($i = 1;; $i++)
{
$uniqueUsername = $firstname.Substring(0, $i) + $lastname + "@" + $domainPart
if (IsUserNameUnique($uniqueUsername))
{
$samAccountName = $firstname.Substring(0, $i) + $lastname
break
}
}
$Context.SetModifiedPropertyValue("userPrincipalName", $uniqueUsername)
if ($Context.IsPropertyModified("sAMAccountName"))
{
$Context.SetModifiedPropertyValue("sAMAccountName", $samAccountName)
}
$Context.LogMessage("The username has been changed to " + $uniqueUsername + ".", "Information")