【发布时间】:2012-03-12 16:37:11
【问题描述】:
我有以下 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 字符:43 + $result = $Host.UI.PromptForChoice
如何捕获其他“选项”,以便在选择其中一个选项时,它会脱离脚本并且不会引发上述错误?
【问题讨论】:
-
你在说什么用户界面?伊势?它没有问题。如果您有任何 UI 代码(winforms?),请尽可能分享。
标签: powershell escaping prompt