简体   繁体   中英

Powershell Switch Statement

I'm trying to write a Switch statement in Powershell like below.

$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 I'm trying to do is that if the user inputs anything other than Y or N, the script should keep prompting until they enter either one of those. What happens right now is 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? Thank You.

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"}
     }

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}
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM