Author Posts

August 10, 2018 at 6:26 am

Hi,

Powershell noob here and struggling to get around this one. I'm creating a new user creation script for my company and want it to create a unique username (firstname.last initial). If it already exits I want to increment the surname by one until a unique username is found. I've got the low so far.

do {
   get-aduser -filter * | select SamAccountName | ForEach-Object {
   
   if ($_.SamAccountName -eq $username) {
   $username = $firstname+($lastname.Substring(0,$i))
   
   $i++
   write-host $username
   }
   else {
   $usernameexists = $false
   
   }
  }
}
until ($usernameexists = $false)

Write-Host "Username is $username" -ForegroundColor Green

It finds a unique username but never exits the do loop. I'm sure it's simple but my brain is flyed @ 2:30 on a Friday afternoon lol.

Thanks for the help.

David.

August 10, 2018 at 8:15 am

All good folks, I did it using a while as below;

$i = 1

while (get-aduser -filter 'SamAccountName -eq $username') {
   
   $username = $firstname+($lastname.Substring(0,$i))
   $i++
   write-host $username
}

PS: I've just learned that using the filter is MUCH quicker than not filtering and then using a ForEach to find a match.

August 10, 2018 at 2:32 pm

For reference, your original problem is that = is not an equality operator in PowerShell. That's -eq.