gpt4 book ai didi

powershell - 停止关闭$ Host.UI.PromptForChoice窗口

转载 作者:行者123 更新时间:2023-12-03 00:11:12 26 4
gpt4 key购买 nike

我正在为工作中的项目制作菜单。以下代码可以正常工作,只有一件事。

如果运行了代码并且有意或无意中关闭了打开的窗口,则do循环停止,并且我没有得到想要的结果。

我的目标是以一种万无一失的方式来确保选择一个选项并且不对其进行旁路。

如果选择了选项1,则循环将根据需要停止。
如果选择了其他任何选项,则会再次提示您选择一个选项。
这告诉我do循环正在工作。

我遗漏了一些东西,一直无法弄清,所以找不到答案。

function Choose_Site {
[int]$Script:Site_Check = "0"
$script:Site_Title = "Please Choose Your Site"
$script:Site_Info = "Please Choose Appropriate Site For This Machine"

$script:Site_Options = [System.Management.Automation.Host.ChoiceDescription[]] @("&1", "&2", "&3", "&4", "&5", "&A", "&B", "&C", "&D", "&E")
[int]$script:Default_Choice = 9
$script:Site_Menu = $Host.UI.PromptForChoice($script:Site_Title, $script:Site_Info, $script:Site_Options, $script:Default_Choice)

switch ($script:Site_Menu) {
0 {Write-Host "1" -ForegroundColor Green; $script:Site_Check = "1"}
1 {Write-Host "2" -ForegroundColor Green}
2 {Write-Host "3" -ForegroundColor Green}
3 {Write-Host "4" -ForegroundColor Green}
4 {Write-Host "5" -ForegroundColor Green}
5 {Write-Host "A" -ForegroundColor Green}
6 {Write-Host "B" -ForegroundColor Green}
7 {Write-Host "C" -ForegroundColor Green}
8 {Write-Host "D" -ForegroundColor Green}
9 {Write-Host "E" -ForegroundColor Green}
}
}

do {
Choose_Site
} until (
$Script:Site_Check -ne "0"
)

最佳答案

如果未设置期望的值,则可以使用FinallyTry..Catch块通过调用函数来执行所需的操作:

function Choose_Site {
[int]$Script:Site_Check = "0"
$script:Site_Title = "Please Choose Your Site"
$script:Site_Info = "Please Choose Appropriate Site For This Machine"

$script:Site_Options = [System.Management.Automation.Host.ChoiceDescription[]] @("&1", "&2", "&3", "&4", "&5", "&A", "&B", "&C", "&D", "&E")
[int]$script:Default_Choice = 9
Try {
$script:Site_Menu = $Host.UI.PromptForChoice($script:Site_Title, $script:Site_Info, $script:Site_Options, $script:Default_Choice)

switch ($script:Site_Menu) {
0 {Write-Host "1" -ForegroundColor Green; $script:Site_Check = "1"}
1 {Write-Host "2" -ForegroundColor Green}
2 {Write-Host "3" -ForegroundColor Green}
3 {Write-Host "4" -ForegroundColor Green}
4 {Write-Host "5" -ForegroundColor Green}
5 {Write-Host "A" -ForegroundColor Green}
6 {Write-Host "B" -ForegroundColor Green}
7 {Write-Host "C" -ForegroundColor Green}
8 {Write-Host "D" -ForegroundColor Green}
9 {Write-Host "E" -ForegroundColor Green}
}
} Finally {
if ($script:Site_Check -eq "0") { Choose_Site }
}
}

您发生问题是因为(我认为)关闭对话框正在终止脚本。即使脚本终止, Finally始终执行。

关于powershell - 停止关闭$ Host.UI.PromptForChoice窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48265553/

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