Active Directory Auto-Generate Username

If you need to generate and test for an available username in Active Directory, this script will allow you to do so up to a specified maximum attempts before requiring manual input. Each loop adds a letter from the first name to the last name for the username. JWayne, JoWayne, JohWayne, JohnWayne.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
CLS
$firstName = "John"
$lastName = "Wayne"
$Global:attempts = 0
$Global:available = $false
$Global:finalName = $null

Function Test-SAM {
    $samAccountName = $($firstName.Substring(0, (1 + $Global:attempts)) + $(($lastName.Split() | select -Last 1) -join ' '))
    Write-Host "Testing $samAccountName"
    Try {
        $userTest = Get-ADUser $samAccountName -ErrorAction SilentlyContinue
    }Catch{
        # Ignore Error - Available Username
        $Global:available = $true
        $Global:finalName = $samAccountName
    }
}

Do {
    Test-SAM
    $Global:attempts +=1
} Until ($Global:available -eq $true -and $Global:attempts -le $firstName.Length -and $Global:attempts -le 2) #specify max attempts here
   
If (!$Global:finalName){
    Write-Host "Could not automagically generate a username, please manually input one below..."
    # do stuff here

    #
}Else{
    Write-Host "Automagically generated username: $Global:finalName"
    # do stuff here

    #
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.