1

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

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 值, - 回收并继续。

谢谢!

4

1 回答 1

2

我不能在 V3 上重现这个,这对 V3 用户来说很好,但在 V2 的情况下,你有没有尝试在 PromptForChoice 调用周围放置一个 try/catch:

try {
    $Host.UI.PromptForChoice($Title, $message, $choices, $defaultChoice)
}
catch [Management.Automation.Host.PromptingException] {
    $defaultChoice
}
于 2012-04-24T20:50:43.873 回答