## Console input with Powershell

I’m looking at building some Powershell scripts that can accept user input to perform different tasks with a wizard style interface. As it happens this is fairly easily achieved with the Read-Host cmdlet. Here’s a quick script showing how such a powershell script may look.

?View Code POWERSHELL
 function mainMenu() { Clear-Host; Write-Host "============"; Write-Host "= MAINMENU ="; Write-Host "============"; Write-Host "1. Press '1' for this option"; Write-Host "2. Press '2' for this option"; Write-Host "3. Press '3' for this option"; Write-Host "4. Press '4' for this option"; }   function returnMenu($option) { Clear-Host; Write-Host "You chose option$option"; Write-Host "Press any key to return to the main menu."; $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown"); } do { mainMenu;$input = Read-Host "Enter a number for an option or type "quit" to finish." switch ($input) { "1" { returnMenu$input; } "2" { returnMenu $input; } "3" { returnMenu$input; } "4" { returnMenu $input; } "quit" { # nothing } default { Clear-Host; Write-Host "Invalid input. Please enter a valid option. Press any key to continue.";$host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown"); } }   } until ($input -eq "quit"); Clear-Host; ### 4 Comments 1. Greg says: Nice job! How do we assign a value to each of the options (to continue running a script?) 2. Rhys says: Hi Greg, Just add the appropriate command in the switch statement. Something like…  switch ($input) { "1" { Get-Service -DisplayName "*SQL*"; returnMenu \$input; } ... /* and so on */ 

If you want to run other powershell scripts here you can do this with…

 & "C:\path\to\script\.ps1"; 

Hope that helps.

Cheers,

Rhys

3. Greg says:

Thanks so much!

4. Rudy says:

I’m wondering how to add a second main menu for a page 2. Called from page 1 say option 5. I keep getting stuck in the same page 1 loop and can’t get out of it. Also on page 2 I’d like another selection 5 to get back to page 1. I’ve tried everything I can to make it work. Any ideas?