我有下面的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
怎樣可以捕獲那些其他的「選項」,這樣,如果他們中的一個選擇,它打出的腳本&不會拋出上面的錯誤?
你在說什麼用戶界面? ISE?它沒有問題。如果您有任何UI代碼(winforms?),請儘可能共享它。 – stej 2012-03-12 20:23:14