2012-03-12 17 views
1

大きなスクリプト内で使用するために以下のpowershellスクリプトを使用しています。PowershellとキャンセルボタンまたはESC

function New-Choice { 
<#  .SYNOPSIS 
       The New-Choice function is used to provide extended control to a script author who writing code 
     that will prompt a user for information. 
     .PARAMETER Choices 
       An Array of Choices, ie Yes, No and Maybe 
     .PARAMETER Caption 
       Caption to present to end user 
     .EXAMPLE 
       PS C:\> New-Choice -Choices 'Yes','No' -Caption "PowerShell makes choices easy"    
     .NOTES 
       Author: Andy Schneider 
       Date: 5/6/2011 
#> 

[CmdletBinding()] 
param(
     [Parameter(Position=0, Mandatory=$True, ValueFromPipeline=$True)] 
     $Choices, 
     [Parameter(Position=1)] 
     $Caption, 
     [Parameter(Position=2)] 
     $Message  
) 

process { 
     $resulthash += @{} 
     for ($i = 0; $i -lt $choices.count; $i++) 
      { 
       $ChoiceDescriptions += @(New-Object System.Management.Automation.Host.ChoiceDescription ("&" + $choices[$i])) 
       $resulthash.$i = $choices[$i] 
      } 
     $AllChoices = [System.Management.Automation.Host.ChoiceDescription[]]($ChoiceDescriptions) 
     $result = $Host.UI.PromptForChoice($Caption,$Message, $AllChoices, 1) 
     $resulthash.$result -replace "&", "" 
     }   
} 

#new-choice -Choices "yes","no","maybe" 
new-choice -Choices "Yes","No","Copy ALL","Cancel (Abort Script)" -Caption "Continue the Copy Process?" 

私ははい、いいえまたはコピーALLが選択されている場合、それは適切な行動をとるようにそれを作りたい、と選択されてキャンセルした場合には、スクリプトを終了します。しかし、キャンセルボタンを選択したり、ESCキーを押したり、ウィンドウを閉じたりするのも同じことです(スクリプトを終了する)。

上記のサンプルでは、​​これらの4つのうちの1つが選択され、OKボタンをクリックすると、正常に実行されます(選択されたものの値が返されます)。ウィンドウが閉じている場合は、[キャンセル]ボタンが選択されているか、ESCキーが入力され、それが次のエラーを生成します。

Exception calling "PromptForChoice" with "4" argument(s): "An error of type "System.Management.Automation.Host.Promptin gException" has occurred." At C:\Documents and Settings\myPC\My Documents\test ui prompt.ps1:34 char:43 + $result = $Host.UI.PromptForChoice <<<< ($Caption,$Message, $AllChoices, 1) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

私はトラップそれらの他の「オプション」をすることができ、それらのいずれかが選択されている場合ようにどのように

、それはスクリプトから壊れている&上記のエラーをスローされませんか?このような

+0

? ISE?問題なく動作します。 UIコード(winforms?)がある場合は、可能であれば共有してください。 – stej

答えて

3

何かが欲しいものを行う必要があります。

何のことをいっているのUI
try { 
    $result = $Host.UI.PromptForChoice($Caption,$Message, $AllChoices, 1) 
} catch [Management.Automation.Host.PromptingException] { 
    exit 
} 
関連する問題