Creating PowerShell Menus

by Nov 8, 2011

PowerShell is console based, so its default menus are console based as well. To offer choices to your users, here is some sample code to create a simple menu:

$title = "Reboot System Now"
$message = "Do you want to reboot your machine now?"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
    "Reboots the system now."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Does not reboot the system. You will have to reboot manually later."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $Host.ui.PromptForChoice($title, $message, $options, 0) 

switch ($result)
    {
        0 {"You selected Yes."
           Restart-Computer -whatif
          }
        1 {"You selected No."}
    }

And this is what the output would look like:

Reboot System Now
do you want to reboot your machine now?
[Y] Yes  [N] No  [?] Help (default is "Y"): ?
Y - Reboots the system now.
N - Does not reboot the system. You will have to reboot manually later.
[Y] Yes  [N] No  [?] Help (default is "Y"): y
You selected Yes.
What if: Performing operation "Restart-Computer" on Target "localhost (DEMO5)".

Note what happens when the user responds by entering "?": the prompt displays a short help text for each available option.

Twitter This Tip!
ReTweet this Tip!