PowerShell "DO...Until" Try and Catch for valid data not working

Viewed 29

I'm trying to use PowerShell to check if a user-provided position number exists. I want to loop this until the user provides a valid position. I am fairly new to PowerShell and I don't understand why it's not working...


#Start Store and Check Budget Position Number User Template#
Clear-Host

Do{
Try{
  # Find the user template
  $budgetpositionnumber = Read-Host " 
    What budget position number is the user filling? 
" 
Write-Host "
You entered budget position number: $budgetpositionnumber
" 
  # Find the position on Your.Domain
  Get-ADuser $budgetpositionnumber
  
}
Catch{
  Write-Host ("Failed to find position number " + $budgetpositionnumber) -ForegroundColor Red -ErrorAction Stop
}
} Until ($budgetpositionnumber -ne $Null)
#End Store and Check Budget Position Number Template#


Even if I enter invalid data, it still continues with the rest of the script. I want it to stop or loop until its' a vaild position number.

##Edited for clarity

1 Answers

"Even if I enter invalid data, it still continues with the rest of the script"

The do loop always ends because it's until condition always evaluates to $true no matter what the input is, this is because any string, even if Empty, is not equal to $null.


The condition:

Until ($budgetpositionnumber -ne $Null)

Should be testing if Get-ADuser found any object instead of testing if there was an input provided in Read-Host.


As for how you can approach the code:

do {
    $userinput = Read-Host "something here..."
    Write-Host "You entered budget position number: $userinput"
    try {
        $found = Get-ADuser $userinput
    }
    catch {
        Write-Warning "No account with Name '$userinput' exists..."
    }
} until ($found)
Related