2011-11-04 131 views
1

我想在下面的Powershell中写一个Switch语句。PowerShell Switch语句

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

我想要做的是,如果用户输入除Y或N以外的任何东西,脚本应该继续提示,直到他们输入其中任何一个。现在发生的情况是当用户输入Y或N以外的任何东西时,会再次提示。但是当他们第二次输入任何字母时,脚本就会退出。它不再要求用户输入他们的输入。是否有可能使用Switch完成此操作?谢谢。

回答

7

我不明白你正在尝试在代码默认做,而是按照你的问题,你希望把它放在一个循环:你可以用递归函数做到这一点

这样做的
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方法:

$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"} 
    } 
+0

谢谢。第一个做了诀窍。欣赏它。 – user1013264

3

你不是在任何地方管道输入。

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

谢谢你。很高兴看到它以不同的方式完成。再次谢谢你。 – user1013264