2

This should be really simple, but I cannot make it work. I'm new to the PowerShell so my mistake is probably obvious. I'm trying to ask a user for an input using a while loop, and prompting the user to try again if what was entered was not numeric. In bash it would look like this:

while read -p "What is the first number? " first; do
if [[ $first = *[[:digit:]]* ]]; then
break   # if $first is numeric, break loop
else
echo "$first is not numeric. Enter a numeric value. "
fi
done

Here's what I have for the PS:

While ($first = (Read-Host "What is the first number?") -as [double]) {
if ($first -eq $null) { Write-Host "Please enter a numeric value." }
else { break }
}

In the example above, I can break the loop fine when a number is entered, but I can't see the Write-Host statement if I type a string.

1
  • the while test is run before the loop is run. that means your if test will prevent the "then" result from ever running. [grin] Commented Nov 19, 2018 at 1:23

2 Answers 2

4

Looking at the While line:

While ($first = (Read-Host "What is the first number?") -as [double]) 

This will only enter/continue the loop body when the input is already a double, because it rolls up the cast to double as part of the loop condition. You want to enter the loop body on any input, and only check if it's a double afterwards. At least, that's what the bash code does:

While ($first = (Read-Host "What is the first number?")) {
    if ( ($first -as [double]) -eq $null) { Write-Host "Please enter a numeric value." }
    else { break }
}

Or you could continue using the cast as part of the condition by negating the whole expression, and thus avoid the need for the awkward break:

While (-not ($first = (Read-Host "What is the first number?") -as [double])) {
    Write-Host "Please enter a numeric value." 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. I think it should be [double] and not double in the first solution though.
@HubertLéveilléGauvin Yes, that was a copy/pasta error.
4

You could use this to keep prompting for a valid number input as you are looking for.

Do {
    "Please enter a numeric value." | Out-Host
    $first = (Read-Host "What is the first number?") -as [double]
} While($null -eq $first)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.