Powershell开关语句
我正在尝试在Powershell中编写一个Switch语句,如下所示Powershell开关语句,powershell,Powershell,我正在尝试在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 =
$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以外的任何内容时,他们会再次收到提示。但是当他们第二次键入任何字母时,脚本就退出了。它不再要求用户输入信息。是否可以使用开关来完成此操作?谢谢。你不会在任何地方用管道传输输入。可以使用递归函数执行此操作:
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}
}
}
我不明白您在代码的默认设置中试图做什么,但根据您的问题,您希望将其放入一个循环中:
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"}
}
也谢谢你。很高兴看到它以不同的方式完成。再次感谢你。