If you don’t mind digging into the .NET Framework, then that’s not your only option. You have most likely encountered something like this in PowerShell:

Typical PowerShell prompt for choice (Image Credit: Jeff Hicks)

You enter one of the bracketed values and something happens. With a little scripting on your part, you can use this same concept in your scripts. The method is part of the builtin $host variable.

The PromptForChoice method (Image Credit: Jeff Hicks)

The PromptForChoice() method has several variations. The parameters we’ll use are essentially a caption, a message prompt, a collection of choices, and the default choice. Let’s play.

The most difficult part of the process is creating the collection of choices. This will be a collection of [System.Management.Automation.Host.ChoiceDescription] objects. First, I’ll initialize an array.

PowerShell

1

$coll=@()

Next, I’ll create one of these ChoiceDescription objects and save the result to a variable.

The text “Choice &1” will be displayed in the prompt. The & indicates what character to use for the choice. Whatever immediately follows will be used as you’ll see. In this case, the number 1 will be the option. What does $c look like?

The choice object (Image Credit: Jeff Hicks)

The HelpMessage is empty, so I’ll set a value.

PowerShell

1

$c.HelpMessage="run choice 1 commands"

The choice object with a help message (Image Credit: Jeff Hicks)

The last step is to add the choice to the collection.

PowerShell

1

$coll+=$c

It doesn’t make sense to have a prompt for choice menu with only a single item, so I’ll add some more.

Note that the ? shows the help messages. Remember when I used the & symbol to indicate what to use for a response? You’ll see those characters in the brackets. In my code, the answer is stored in $r. The value will be an integer reflecting the index number of the selected array member. You can use a simple Switch statement to process the results.

PowerShell

1

2

3

4

5

6

7

8

Switch($r){

0{Write-Host"I am the 1st choice"-foregroundcoloryellow}

1{Write-Host"I am the 2nd choice"-foregroundcoloryellow}

2{Write-Host"I am the 3rd choice"-foregroundcoloryellow}

3{Write-Host"I am the 4th choice"-foregroundcoloryellow}

4{Write-Host"I am the 5th choice"-foregroundcoloryellow}

5{Write-Host"Thank you"-ForegroundColorgreen}

}

Remember that arrays start counting at 0. Here’s the complete script in action.

The choice prompt in action (Image Credit: Jeff Hicks)

I am merely displaying a message but you could invoke whatever PowerShell commands you needed to.

But we can take advantage of PowerShell’s ability to extend objects and add some action to our object choices. Here’s a more practical example.