Search code examples
powershellactive-directory

User creation script avoid duplicate username


I would like to do an Active Directory search using PowerShell to discover if the username I want to create is already in use,. If it is already in use I want the script to add the following number at the and of the user name.

Import-Module ActiveDirectory
    $family= Mclaren
    $first= Tony
    #This part of the script will use the first 5 letters of $family and the first 2 letters of $first and join them together to give the $username of 7 letters
    $username = $family.Substring(0, [math]::Min(5, $family.Length)) + $first.Substring(0, [math]::Min(2, $first.Length)) 
  • The user name will look like "mclarto" base on that (username take the 5 first letters of the family name plus 2 charof the firstname) a seach is done in AD.
  • If there is no result, "mclarto" will be taken as $username without any number at the end.
  • If the search find other users with the same username, the username should take the following number, in this case it would be "mclarto1".
  • If "mclarto1" already exist then "mclarto2" should be use and so on.

Solution

  • I think this will get you close, it uses the ActiveDirectory module.

    Import-Module ActiveDirectory
    
    $family = "Mclaren*"
    
    # Get users matching the search criteria
    $MatchingUsers = Get-ADUser -Filter 'UserPrincipalName -like $family' 
    
    if ($MatchingUsers)
    {
        # Get an array of usernames by splitting on the @ symbol
        $MatchingUsers = $MatchingUsers | Select -expandProperty UserPrincipalName | %{($_ -split "@")[0]}
    
        # loop around each user extracting just the numeric part
        $userNumbers = @()
        $MatchingUsers | % { 
            if ($_ -match '\d+')
            {
                $userNumbers += $matches[0]
            }
        }
    
        # Find the maximum number
        $maxUserNumber = ($userNumbers | Measure-Object -max).Maximum
    
        # Store the result adding one along the way (probably worth double checking it doesn't exist)
        $suggestedUserName = $family$($maxUserNumber+1)
    }
    else
    {
        # no matches so just use the name
        $suggestedUserName = $family
    }
    
    # Display the results
    Write-Host $suggestedUserName