I've got a function that checks AD before attempting to "choose" a username; it'll start by assuming first initial+last name, and see if that's already in AD.
If it is, it'll add letters from the first name until it finds an unused username. If it exhausts all letters in the first name, it'll tack an incrementing number on the end (i.e. jdoe, jodoe, johdoe, johndoe, johndoe1, johndoe2, etc.):
Note: this assumes you have the first name as $FirstName
and the last name as $LastName
When attempting to run script then I got the following the error message:
Get-ADUser : Cannot find an object with identity: 'JDoe' under: >'DC=contoso,DC=com'. At line:18 char:31 + $usernameExists = Get-ADUser <<<< $username -ErrorAction >SilentlyContinue | format-wide IsValid + CategoryInfo : ObjectNotFound: (JDoe:ADUser) [Get-ADUser], >ADIdentityNotFoundException + FullyQualifiedErrorId : Cannot find an object with identity: 'JDoe' >under: >'DC=contoso,DC=com'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser Setting username as JDoe
I am assuming there is a problem related to the IsValid
parameter?
$firstname_auto = $firstname.ToLower()
$lastname_auto = $lastname.ToLower()
$FirstNameLength = ($firstname_auto | Measure-Object -Character).Characters
$letterCount = 0
$username = ''
#Try to spell out the entire first name until we can get a unique username
do {
$letterCount++
$usernameExists = $false
$username = "$($firstname_auto.Substring(0,$letterCount))$($lastname_auto)"
$usernameExists = Get-ADUser $username -ErrorAction SilentlyContinue | format-wide IsValid
if ($usernameExists -eq $true) {
Write-Verbose "$username exists in AD. Trying again."
}
} until (($usernameExists -eq $false) -OR ($letterCount -eq $FirstNameLength))
#If we've used all the letters in the first name, and the username still isn't unique,
#start counting until we find one that is.
if ($usernameExists -eq $true) {
$usernameNumber = 0
Write-Verbose "Exhausted all non-numeric options! Trying with numbers."
do {
$usernameNumber++
$usernameExists = $false
$username = "$($firstname_auto.Substring(0,$letterCount))$lastname_auto$usernameNumber"
$usernameExists = Get-ADUser $username -ErrorAction SilentlyContinue | format-wide IsValid
if ($usernameExists -eq $true) {
Write-Verbose "$username already exists in AD. Trying again."
}
} until ($usernameExists -eq $false)
}
Write-host "Setting username as $username" -foregroundcolor Green