Powershell&取消按钮或ESC

时间:2012-03-12 16:37:12

标签: powershell escaping prompt

我有以下的powershell脚本,我试图适应在更大的脚本中使用。

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键,则会生成以下错误:

  

使用“4”参数调用“PromptForChoice”的异常:“错误   键入“System.Management.Automation.Host.Promptin gException”   发生了。“在C:\ Documents and Settings \ myPC \ My Documents \ test ui   prompt.ps1:34 char:43   + $ result = $ Host.UI.PromptForChoice&lt;&lt;&lt;&lt; ($ Caption,$ Message,$ AllChoices,1)       + CategoryInfo:NotSpecified:(:) [],MethodInvocationException       + FullyQualifiedErrorId:DotNetMethodException

如何捕获其他“选项”,以便在选择其中一个选项时,它会突破脚本&amp;不抛出上述错误?

1 个答案:

答案 0 :(得分:3)

这样的事情应该做你想做的事情:

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