我有一个函数返回一个选定的值,除非提示被关闭。功能是:
function Read-Choice {
#.Synopsis
# Prompt the user for a choice, and return the (0-based) index of the selected item
#.Parameter Message
# The question to ask
#.Parameter Choices
# An array of strings representing the "menu" items, with optional ampersands (&) in them to mark (unique) characters to be used to select each item
#.Parameter DefaultChoice
# The (0-based) index of the menu item to select by default (defaults to zero).
#.Parameter Title
# An additional caption that can be displayed (usually above the Message) as part of the prompt
#.Example
# Read-Choice "WEBPAGE BUILDER MENU" "Create Webpage","View HTML code","Publish Webpage","Remove Webpage","E&xit"
PARAM([string]$message, [string[]]$choices, [int]$defaultChoice=0, [string]$Title=$null )
if($choices[0].IndexOf('&') -lt 0) {
$i = 0;
$choices = $choices | ForEach-Object {
if($_ -notmatch '&.') { "&$i $_" } else { $_ }
$i++
}
}
$Host.UI.PromptForChoice( $Title, $message, [Management.Automation.Host.ChoiceDescription[]]$choices, $defaultChoice )
}
我称之为:
$SetDeletes = read-choice "Delete Files" "Recycle","Kill","E&xit" 0 $message
提示用户选择0 Recycle,1 Kill或Exit。如果选择了这三个中的一个并且用户点击OK,则返回所选的任何值(0,1或2)。但是,如果提示已关闭,或者用户点击取消,则脚本将中止并显示如下消息:
使用“4”参数调用“PromptForChoice”的异常:“错误 键入“System.Management.Automation.Host .PromptingException” 发生“。
如何捕获和处理提示上的Cancel键?如果没有选择,我想默认为0值, - 回收并继续。
谢谢!
答案 0 :(得分:2)
我不能在V3上重复这一点,这对V3用户来说很好,但在V2的情况下,你试过在PromptForChoice调用周围尝试一下try / catch:
try {
$Host.UI.PromptForChoice($Title, $message, $choices, $defaultChoice)
}
catch [Management.Automation.Host.PromptingException] {
$defaultChoice
}