Custom Console-Based Dialog

by Mar 3, 2022

Using 3rd party dialogs isn’t always a good choice. Reusing the built-in PowerShell dialogs can be much more fun. Here is a function called Show-ConsoleDialog that lets you easily compose such a dialog with all the options you need.

The dialog shows equally well in pure console environments (like PowerShell 7 or VSCode) and PowerShell ISE (popping up as custom dialog).

function Show-ConsoleDialog
    $Title = 'PowerShell',
    # do not use choices with duplicate first letter
    # submit any number of choices you want to offer
    $Choice = ('Yes', 'No')

  # turn choices into ChoiceDescription objects
  $choices = foreach ($_ in $choice)
    [System.Management.Automation.Host.ChoiceDescription]::new("&$_", $_)

  # translate the user choice into the name of the chosen choice
  $choices[$host.ui.PromptForChoice($title, $message, $choices, 1)].Label.Substring(1)

You can use it like this:

$result = Show-ConsoleDialog -Message 'Restarting Server?' -Title 'Will restart server for maintenance' -Choice 'Yes','No','Later','Never','Always'

switch ($result)
    'Yes'        { 'restarting' }
    'No'         { 'doing nothing' }
    'Later'      { 'ok, later' }
    'Never'      { 'will not ask again' }
    'Always'     { 'restarting without notice now and ever' }

The return value is always the name of the choice the user picked. Use a switch statement, for example, to respond to the user choice.

Note also that the first letter of each choice turns into a keyboard shortcut, so do not use choices with duplicate first letters.

Twitter This Tip! ReTweet this Tip!