Check if a username exists

Welcome Forums General PowerShell Q&A Check if a username exists

This topic contains 2 replies, has 2 voices, and was last updated by  Don Jones 2 months, 1 week ago.

  • Author
    Posts
  • #108121

    David C
    Participant

    My Achievements

    No Achievements Yet!

    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.

  • #108124

    David C
    Participant

    My Achievements

    No Achievements Yet!

    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.

  • #108193

    Don Jones
    Keymaster

    My Achievements

    PUBLISHED IconHELPFUL IconSUPER HELPFUL Icon

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

You must be logged in to reply to this topic.

Skip to toolbar