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 リサイクル、1 キル、または終了のいずれかを選択するよう求められます。これら 3 つのうちの 1 つが選択され、ユーザーが [OK] をクリックすると、選択された値 (0、1、または 2) が返されます。ただし、プロンプトが閉じられた場合、またはユーザーがキャンセルを押した場合、スクリプトは次のようなメッセージで中止されます。

"4" 個の引数を指定して "PromptForChoice" を呼び出し中に例外が発生しました: "タイプ "System.Management.Automation.Host .PromptingException" のエラーが発生しました。

プロンプトのキャンセル キーをトラップして処理するにはどうすればよいですか? 何も選択しない場合は、デフォルトで 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 に答える