Script Repository


Check whether username is unique

May 05, 2021
119

The script checks whether the username of an account is unique in AD domain and does not match the prefixes of any proxy addresses in Exchange. Usernames are generated as Last Name plus the first initial of the First name. If the current username is not unique the next letter of the first name will be added. To execute the script, create a business rule triggering Before creating a user.

Edit Remove
PowerShell
function IsUniqueInAD($sAMAccountName, $domainName)
{
    $searcher = $Context.BindToObject("Adaxes://$domainName")
    $searcher.SearchFilter = "(&(sAMAccountType=805306368)(|(sAMAccountName=$sAMAccountName)(proxyAddresses=smtp:$sAMAccountName@*)))"
    $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
    $searcher.SizeLimit = 1
    $searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
    
    try
    {
        $searchResultIterator = $searcher.ExecuteSearch()
        $searchResults = $searchResultIterator.FetchAll()
        
        return $searchResults.Length -eq 0
    }
    finally
    {
        # Release resources
        if ($searchResultIterator){ $searchResultIterator.Dispose() }
    }
}

function IsUniqueInExchangeOnline($userName)
{
    # Search users in Exchange Online
    $recipient = Get-Recipient -Filter "EmailAddresses -like 'smtp:$userName@*'" -ResultSize 1 -WarningAction SilentlyContinue
    return $NULL -eq $recipient
}

# Get sAMAccountName
$userName = $Context.GetModifiedPropertyValue("sAMAccountName");

try
{
    $session = $Context.CloudServices.CreateExchangeOnlinePSSession()
    Import-PSSession $session -CommandName "Get-Recipient" 

    # Check whether sAMAccountName is unique
    $domain = $Context.GetObjectDomain("%distinguishedName%")
    if ((IsUniqueInAD $userName $domain) -and (IsUniqueInExchangeOnline $userName))
    {
        return
    }
     
    # Get the first and last names
    $firstName = $Context.GetModifiedPropertyValue("givenName")
    $lastName = $Context.GetModifiedPropertyValue("sn")
     
    $uniqueUserName = $NULL
    for ($i = 2; $i -le $firstName.Length; $i++)
    {
        $firstNamePart = $firstName.SubString(0, $i)
        $generatedUserName = "$lastName$firstNamePart"
        if ((IsUniqueInAD $generatedUserName $domain) -and (IsUniqueInExchangeOnline $generatedUserName))
        {
            $uniqueUserName = $generatedUserName
            break
        }
    }
     
    # If sAMAccountName is not unique, add a digit to it
    if ($NULL -eq $uniqueUserName)
    {
        for ($i = 1; $True; $i++)
        {
            $uniqueUserName = "$lastName$firstName$i"
            if ((IsUniqueInAD $uniqueUserName $domain) -and (IsUniqueInExchangeOnline $uniqueUserName))
            {
                break
            }
        }
    }
     
    # Update sAMAccountName
    $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 " + $uniqueUserName `
      + ".", "Information")
}
finally
{
    # Close the remote session
    if ($session) { Remove-PSSession $session }
}

Comments ( 0 )
No results found.
Leave a comment