1

I have a while loop in powershell that checks for input

:checker while($choice1 = read-host "Do you want to continue? [Y/N/C]"){
    switch ($choice1){
        "N"{Echo Ok; $temporary = "Exit"; break :checker}
        "Y"{Echo Ok; $temporary = "Continue"; break :checker}
        "C"{Echo Ok; $temporary = "Cancel"; break :checker}
        default{"Invalid input"}
    }
}

However, no matter the input, the while loop never gets broken. Is there an issue with my code, or is there a different way to do this that will ensure the correct things to happen?

2 Answers 2

2

Instead of break :checker, you should have break checker to break out to the outermost loop. It's just breaking out of the switch statement currently.

Sign up to request clarification or add additional context in comments.

1 Comment

Nicely done; it's unfortunate that optionally using : before the label name isn't supported (as of PowerShell 7.0); this GitHub suggestion aims to change that.
0

here is a variant on the idea. it works by setting $Choice to the user input ... and, if the input is not valid, setting $Choice to a blank string so that the while loop will continue.

i removed the call to ok since you didn't provide that code. [grin]

the code ...

$Choice = ''
while ([string]::IsNullOrEmpty($Choice))
    {
    $Choice = Read-Host 'Do you want to continue? [Y/N/C] '
    switch ($Choice)
        {
        "N"{$temporary = "Exit"; break}
        "Y"{$temporary = "Continue"; break}
        "C"{$temporary = "Cancel"; break}
        default{$Choice = ''; "Invalid input"}
        }
    }

$Choice
$Temporary

output ...

Do you want to continue? [Y/N/C] : t
Invalid input
Do you want to continue? [Y/N/C] : y
y
Continue

3 Comments

Oops, I meant to do echo Ok not ok my bad! I'll fix that in the latest edit
@Asian - that is an easy-to-make error. [grin] does my code work as a different way that you asked for?
glad to hear that it works ... & you are most welcome! [grin]

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.