Powershell -输入时捕获取消

sqxo8psd  于 2023-01-20  发布在  Shell
关注(0)|答案(1)|浏览(136)

我有一个函数,除了提示符关闭时,它会返回一个选定的值。该函数是:

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)。但是,如果关闭提示,或者用户单击cancel,则脚本将中止,并显示如下消息:
使用"4"个参数调用"PromptForChoice"时发生异常:发生类型为"系统.管理.自动化.主机.提示异常"的错误。
如何捕获和处理提示符上的取消键?如果没有选择,我想默认为0值,-回收并继续。
谢谢!

fjnneemd

fjnneemd1#

我无法在V3上重现这一点,这对V3用户来说很好,但在V2的情况下,您是否尝试过在PromptForChoice调用周围放置一个try/catch:

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

相关问题