I have the following powershell script that I am trying to adapt for use within a larger script.
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?"
I want to make it so that if Yes, No or Copy ALL are selected, it takes the appropriate action, and if Cancel is selected it ends the script. However, I would also like for it to make the selecting of the Cancel button, hitting the ESC key, or closing out the window all do the same thing (end the script) as well.
On the above sample, it runs fine if one of those four are selected, and you click on the OK button (it returns the value of what was selected). However, if the Window is closed, the Cancel button is selected or the ESC key is typed, it generates the following error:
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
How can I trap those other “options” so that if one of them is selected, that it breaks out of the script & doesn’t throw the above error?
Something like this should do what you want: