'When generating a unique username in Active Directory, numbers do not increment correctly

I am updating a script we use to generate new users and update users based on a csv we download from a feed every night. I need to generate a unique username for each user, using a preferred or first name and last name. When I generate the username, I am using a number at the end that is supposed to increment by one for each new user. I am running into an issue with the incremental number part though. When the usernames generate, they generate like username1, username12, username123 instead of username1, username2, username3, etc. When I build the function, it looks like this:

function NewAdUser ($hruser)
{
    $stat = @('Create')
    
    # First, Last, and EEID fields must exist
    if (-not $hruser.First -or -not $hruser.Last -or -not $hruser.EEID)
    {
        Write-Host -fore Cyan -back Red '- First, Last, and/or EEID not found in HR feed - cannot create user'
        $stat += 'CreateFail-NoFirstLastEeid'
        return ($stat -join '/')
    }

    if ($hruser.HrlyOrSal -eq 'H') { $tgt_ou = $hrly_ou }
    else { $tgt_ou = $emp_ou }

    $empID = $hruser.EmployeeID.PadLeft(5,"0")
    
    if ($hruser.PreferredName) { $userDisplayName = $hruser.PreferredName + ' ' + $hruser.Last }
    else { $userDisplayName = $hruser.First + ' ' + $hruser.Last }

#Generate Unique sAMAccountName based on Preferred or First and Last

    if ($hruser.PreferredName){
         
            $userSAM = $hruser.PreferredName + '.' + $hruser.Last}
    else{ 
            $userSAM = $hruser.First + '.' +  $hruser.Last}

    $g = 1
 

    While ((Get-ADUser -Filter {sAMAccountName -eq $userSAM}) -ne $null)
        {
            $userSAM = $userSAM + $g
            $g++
        }
    
#Generate Unique Common Name based on Preferred or First and Last

    if ($hruser.PreferredName){

            $name = $hruser.PreferredName + ' ' + $hruser.Last}

    else{ 

            $name = $hruser.First + ' ' +  $hruser.Last}
    
    $j = 1

        While((Get-ADUser -Filter {Name -eq $name}) -ne $null)
        {
            $name = $name + $j
            $j++
        }



    #$userSAM = $hruser.First.ToLower() + '.' + $hruser.Last.ToLower()
    $userUPN = $userSAM + "@domain.com"
    $userDisplayName = (Get-Culture).TextInfo.ToTitleCase($userDisplayName.ToLower())
    $userLast = (Get-Culture).TextInfo.ToTitleCase($hruser.Last.ToLower())
    $userFirst = (Get-Culture).TextInfo.ToTitleCase($hruser.First.ToLower())
    
    try
    {
        $newaduser_params = @{
            'Name' = $name
            'Path' = $tgt_ou
            'Enabled' = $false
            'sAMAccountName' = $userSAM
            'displayName' = $userDisplayName
            'Surname' = $userLast
            'givenName' = $userFirst
            'UserPrincipalName' = $userUPN
            'EmployeeID' = $empID
            'ErrorAction' = 'Stop'
        }
        New-ADUser @newaduser_params
    }
    catch 
    {
        Write-Host -fore Cyan -back Red '- Failed to create new user'
        $stat += 'CreateFail'
    }

    return ($stat -join '/')
}

What am I doing wrong here?



Solution 1:[1]

Your problem is in your loop:

While((Get-ADUser -Filter {Name -eq $name}) -ne $null)
{
    $name = $name + $j
    $j++
}

You're creating the new username using $name, but you're also overwriting $name every time. So you set $name to "username1". Then on the next iteration of the loop, you set $name to $name + $j, which is equivalent to "username1" + "2".

You need to store the original, non-numbered username in a separate variable and use that each time you increment the number:

$j = 1

$originalName = $name

While((Get-ADUser -Filter {Name -eq $name}) -ne $null)
{
    $name = $originalName + $j
    $j++
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriel Luci