Search code examples
loopspowershelldsquery

Verify user in AD, if user not found, ask again


I am trying find a specific user in AD using samaccountname if i type in an incorrect account i want the question to repeat until it finds the user, tells me the username and pauses until a key is pressed. Here is what i have so far and its not working. I am still a noob at this.

do{
$User=Read-Host "Enter SamAcountname"}

if (dsquery user -samid $User)
{
trap {$_ | write-host "Found user $_"
}
else 
{
trap {$_ | write-host "User not found!" 
}
{
until ( $_-eq "found user")
}

Write-Host "Press any key to continue ..."

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Solution

  • This should do it:

    $prompt = "enter samaccountname"
    
    do{    
        $User = Read-Host $prompt
    } while (!$(dsquery user -samid $User;$prompt="User '$user' was not found, try again"))
    
    $User