Get-Choice.ps1 – Displays PowerShell style menu and gets a user choice


##
## Author   : Roman Kuzmin
## Synopsis : Displays PowerShell style menu and gets a user choice
## Modified : 2006.10.13
##
## Returns a choice index
## -caption <string>: menu caption
## -message <string>: menu message
## -choices <string[]>: pairs: item1, help1, item2, help2, ...
## -defaultChoice <int>: default choice index
##
## *) Choice keys are indicated by '&' in menu items.
##

param
(
    [string]$caption    = 'Confirm',
    [string]$message    = 'Are you sure you want to continue?',
    [string[]]$choices  = ('&Yes', 'Continue', '&No', 'Stop'),
    [int]$defaultChoice = 0
)

$choiceDescriptions = @()
for($i = 0; $i -lt $choices.Count; $i += 2)
{
    $c = [System.Management.Automation.Host.ChoiceDescription]$choices[$i]
    $c.HelpMessage = $choices[$i + 1]
    $choiceDescriptions += $c
}

$Host.UI.PromptForChoice($caption, $message, [System.Management.Automation.Host.ChoiceDescription[]]$choiceDescriptions, $defaultChoice)

EDIT: See also the modified version for multiple choices here.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: