Try another username if exists

I have thrown together a powershell script that uses the following logic:

Enter desired username?

If doesnt exist execute New-ADUser 

If it does exist ........

And this is where I get stuck.  If it does exist how can I ask for the user to try another username until the result is false

Heres part of the script:

$name = read-host "Enter the username"
$usercheck = $null
# check if username exists already in AD
$usercheck = Get-ADUser -Filter {sAMAccountName -eq $name}

# Check search result to see if it's Null and then create the user
If ($usercheck -eq $null) {

Write-Host "You can use this username"
}
# If it's not null, print out to screen
Else { Write-Host "User: "$_.SamAccountName "already exists!"}

February 17th, 2015 2:55pm

Are you looking to just loop it up until you want to stop?

do {
    stuff
} while ($name -ne "stop")

Free Windows Admin Tool Kit Click here and download it now
February 17th, 2015 2:59pm

Use a loop and exit when the logic is satisfied.

while($true){
    $x=Read-Host 'Enter X to quit'
    if($x -eq 'X'){break}
}

February 17th, 2015 3:00pm

Hi,

Here's an example you can play with:

$found = $false

Do {

    $usernameToCheck = Read-Host 'Enter the desired username'

    If (Get-ADUser -Filter "SamAccountName -eq '$usernameToCheck'") {
        
        #Do things here if the username is in use

        Write-Warning "$usernameToCheck is already in use."

    } Else {

        #Do things here if the username is available

        $found = $true

    }

} Until ($found)

Free Windows Admin Tool Kit Click here and download it now
February 17th, 2015 3:03pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics