2012-03-12 136 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?" 

我想让它这样,如果是,否或复制所有被选中时,它将采取适当的行动,而如果取消选中它结束脚本。不过,我也希望它能够选择取消按钮,按下ESC键或关闭窗口,都可以做同样的事情(结束脚本)。

在上面的示例中,如果选择其中一个,它将运行正常,并且您单击确定按钮(它会返回所选内容的值)。但是,如果窗口关闭,取消按钮选择或按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 2012-03-12 20:23:14

回答

3

像这样的东西应该做你想要什么:

try { 
    $result = $Host.UI.PromptForChoice($Caption,$Message, $AllChoices, 1) 
} catch [Management.Automation.Host.PromptingException] { 
    exit 
}