gpt4 book ai didi

powershell - 为什么我的 Switch 语句提示用户输入时没有正确退出?

转载 作者:行者123 更新时间:2023-12-02 12:40:20 25 4
gpt4 key购买 nike

我编写了一个 Switch 语句,如果用户输入 Y 或 N 以外的任何内容,脚本应不断提示,直到他们输入这些字母之一。

$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 以外的任何内容时,他们会再次收到提示。但是当他们第二次输入任何字母时,脚本就会退出。它不再要求用户输入。是否可以使用 Switch 来完成此任务?

最佳答案

我不明白您在代码的默认情况下想要做什么,但根据您的问题,您想将其放入循环中:

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

关于powershell - 为什么我的 Switch 语句提示用户输入时没有正确退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8015637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com