0

I'm struggling with to get the same Read-Host if the user put in an invalid input. I have tried many different solution but can't get it to work.

My example is a simple yes/no script. But I want it to give me the Read-Host again if it's not ja/nej. I'ts also okay to get a more universal solution, like if wrong input tray again kind of way.

Write-Host "Er du født før 1. januar 2000?";
$Readhost = Read-Host "ja/nej"
switch ($Readhost)
{
ja {write-host "Så er du over 18 år gammel"}
nej {write-host "Så er du yngere end 18 år"}
default {write-host ”Svar på spørgsmålet!”}
} 
0

2 Answers 2

3

You need a while loop!

Write-Host "Er du født før 1. januar 2000?";
$Readhost = ""

while ($Readhost -notin "ja", "nej") {
    $Readhost = Read-Host "ja/nej"

    switch($Readhost) {
        ja {write-host "Så er du over 18 år gammel"}
        nej {write-host "Så er du yngere end 18 år"}
    } 
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'd keep the default to inform the user why asking again.
0

If you have a pre-defined set of options like "yes/no", then consider using a menu to avoid invalid input. For example:

$selectedFruit = $host.UI.PromptForChoice('Select a Fruit', "Which fruit is your favorite?", ('&Apple', '&Melon', 'Man&go','&Quit'), 0)

switch($selectedFruit)
{
    0 {Write-Host "You chose 'Apple'"}
    1 {Write-Host "You chose 'Melon'"}
    2 {Write-Host "You chose 'Mango'"}
}

In the console, this produces a menu like this:

enter image description here

As you can see it will continue to prompt the user if they enter an incorrect value (or select the Quit option). If you don't want a default value, change the 0 in PromptForChoice to -1.

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.