Create a custom "Are you sure" prompt in PowerShell

There will be times when you want to ask someone if they're sure about proceeding, or ask them to make some other choice. You could display a prompt using Write-Host, and collect input using Read-Host... but then you have to validate the input, can't easily restrict someone to a set of choices... yuck. There's a better (although very non-obvious) way: Use PowerShell's built-in choice prompting.

$title = 'What should I do?'
$prompt = 'Should I [A]bort or [R]etry?'
$abort = New-Object System.Management.Automation.Host.ChoiceDescription '&Abort','Aborts the operation'
$retry = New-Object System.Management.Automation.Host.ChoiceDescription '&Retry','Retries the operation'
$options = [System.Management.Automation.Host.ChoiceDescription[]] ($abort,$retry)
 
$choice = $host.ui.PromptForChoice($title,$prompt,$options,0)

At the end, $choice will contain 0 for the first choice (abort) and 1 for the second (retry). That last 0 sets option 0 (abort) to be the default, which is what you get if the user just hits Enter. Try it out - this is a non-destructive example, and it's a lot clearer when you can actually see it working.

The trick is remembering what order you added the options, which is on line 5, above. Because I added $abort first, it becomes option 0 and the second, $retry, becomes option 1. You can add more than one - more than about 4, however, makes the prompt pretty ugly and hard to read, I think.

When you create the options (lines 3 and 4), put an ampersand (&) before the letter that will be the input for that option. In other words, what I've done means you can press "A" for abort, and "R" for retry, because the ampersand precedes those letters in the prompt name.

The longer version of the prompt - "Aborts the operation" - will be displayed if the user enters ? as their choice, instead of A or R. So those longer descriptions should do a good job of succinctly explaining what the option will do.

Enjoy!

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×