Powershell-输入时捕获取消

Powershell-输入时捕获取消,powershell,prompt,choice,Powershell,Prompt,Choice,我有一个函数,它返回一个选定的值,提示关闭时除外。功能是: 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 th

我有一个函数,它返回一个选定的值,提示关闭时除外。功能是:

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回收、1终止或退出。如果选择了这三个选项中的一个,并且用户点击OK,则返回所选的任何值(0、1或2)。但是,如果提示关闭,或者如果用户点击cancel,脚本将中止,并显示如下消息:

$SetDeletes = read-choice "Delete Files" "Recycle","Kill","E&xit" 0 $message
使用“4”参数调用“PromptForChoice”异常:“错误” 类型“System.Management.Automation.Host.PromptingException”已被删除 发生了。”

如何捕获和处理提示符上的取消键?如果没有选择,我希望默认值为0,-Recycle并继续


谢谢

我无法在V3上重新编程,这对V3用户来说很好,但在V2的情况下,您是否尝试过在PromptForChoice调用中加入try/catch:

try {
    $Host.UI.PromptForChoice($Title, $message, $choices, $defaultChoice)
}
catch [Management.Automation.Host.PromptingException] {
    $defaultChoice
}