Asking Script Users for a Choice

How to use PowerShell's built-in prompting system to ask users for a decision.

Don Jones

July 5, 2011

1 Min Read
ITPro Today logo in a gray background | ITPro Today

Try running this (type carefully) in the PowerShell console:

Get-Process | Stop-Process -confirm


You'll get a text prompt asking you if you're sure. Your choices will be "Y"es, Yes to "A"ll, "N"o, or No to Al"L". This prompting mechanism is built into PowerShell, and its exact presentation depends on the host in which you run it. Try the exact same thing in the PowerShell ISE, for example, and you get a dialog box with buttons for the various choices. This ability for PowerShell hosts to automatically present the prompt is very useful, and it's something you can leverage in your own scripts.

For example:

$caption = "Choose Action";$message = "What do you want to do?";$restart = new-Object System.Management.Automation.Host.ChoiceDescription "&Restart","Restart";$shutdown = new-Object System.Management.Automation.Host.ChoiceDescription "&Shutdown","Shutdown";$choices = [System.Management.Automation.Host.ChoiceDescription[]]($restart,$shutdown);$answer = $host.ui.PromptForChoice($caption,$message,$choices,0)switch ($answer){    0 {"You entered restart"; break}    1 {"You entered shutdown"; break}}


Notice the use of the ampersand in the prompt strings. The letter following the ampersand becomes the shortcut key for that choice: "R" for Restart and "S" for Shutdown, in this case.

Because this kind of prompting is automatically handled by PowerShell hosts, it's superior to constructing your own dialog boxes or text prompts. Using this technique, your prompt will display appropriately for whatever host your code is running inside of.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like