2

Does anyone know why this while statement will not return TRUE when I enter "A" or "PTR" into the Read-Host?

$lookupDecision = Read-Host "Do you want results for A or PTR: "

while( $lookupDecision -ne "A" -or $lookupDecision -ne "PTR" ) {
    $lookupDecision = Read-Host "Invalid input! Enter A or PTR: "
}
0

2 Answers 2

4

This statement does return TRUE, and will do so no matter what you enter. If you enter A, it results in TRUE because A is not equal to PTR. If you enter PTR it results in TRUE because it's not equal to A. Anything else is not equal to both of them.

The problem here is that you want it eventually return FALSE, so you can move past the while loop to the next section of code. To do this, you need a -and instead of a -or.

$lookupDecision = Read-Host "Do you want results for A or PTR: "

while( $lookupDecision -ne "A" -and $lookupDecision -ne "PTR" ) {
    $lookupDecision = Read-Host "Invalid input! Enter A or PTR: "
}
Sign up to request clarification or add additional context in comments.

6 Comments

[string]::Compare() is unnecessary here, the default mode of all comparison operators in PowerShell is case-insensitivity when operating on strings. You have to state case-sensitive comparison operations explicitly, ie. "a" -cne "A"
@MathiasR.Jessen I was expecting that, but when I tested the first version before posting I just typed "a" and it failed. I had to use A to get it to work, and this fixed it. I think it depends on the version of PowerShell.
Interesting, what version/platform did you see this behavior with? In any case, the idiomatic powershell solution here is -ine rather than [string]::Compare()
Win8.1 PS4.0, which I expect would support that.
... and now I can't reproduce the problem :( I'll just delete the 2nd part.
|
0

Do while's are awesome for prompting users for input

do {
     $lookupDecision = Read-Host "Do you want results for A or PTR: "
} while ($lookupDecision -ne "A" -And $lookupDecision -ne "PTR")

1 Comment

This still has the bad -or and won't work. Also, it can confuse users if the prompt never changes. Better to have something to indicate the problem.

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.