user1013264
user1013264

Reputation: 71

Why isn't my Switch statement prompting for user input exiting properly?

I have written a Switch statement where, if the user inputs anything other than Y or N, the script should keep prompting until they enter either one of those letters.

$Prompt = Read-host "Should I display the file contents c:\test for you? (Y | N)" 
Switch ($Prompt)
     {
       Y {Get-ChildItem c:\test}
       N {Write-Host "User canceled the request"}
       Default {$Prompt = read-host "Would you like to remove C:\SIN_Store?"}
     }

What happens now, however, is that when the user inputs anything other than Y or N, they get prompted again. But when they type any letter the second time, the script just exits. It doesn't ask the user for their input anymore. Is it possible to accomplish this using Switch?

Upvotes: 2

Views: 13833

Answers (2)

manojlds
manojlds

Reputation: 301327

I don't understand what you are trying to do in the default in your code, but as per your question, you want to put it in a loop:

do{

$Prompt = Read-host "Should I display the file contents c:\test for you? (Y | N)" 
Switch ($Prompt)
 {
   Y {Get-ChildItem c:\test}
   N {Write-Host "User canceled the request"}
   Default {continue}
 }

} while($prompt -notmatch "[YN]")

Powershell way of doing this:

$caption="Should I display the file contents c:\test for you?"
$message="Choices:"
$choices = @("&Yes","&No")

$choicedesc = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] 
$choices | foreach  { $choicedesc.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList $_))} 


$prompt = $Host.ui.PromptForChoice($caption, $message, $choicedesc, 0)

Switch ($prompt)
     {
       0 {Get-ChildItem c:\test}
       1 {Write-Host "User canceled the request"}
     }

Upvotes: 7

JNK
JNK

Reputation: 65187

You aren't piping that input anywhere. You can do this with a recursive function:

Function GetInput
{
$Prompt = Read-host "Should I display the file contents c:\test for you? (Y | N)" 
Switch ($Prompt)
     {
       Y {Get-ChildItem c:\test}
       N {Write-Host "User canceled the request"}
       Default {GetInput}
     }
}

Upvotes: 3

Related Questions