Asking Script Users for a Choice

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.

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive