Advertisement
Lee_Dailey

function_Get-MenuChoice [simplified]

Sep 3rd, 2019
1,538
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Get-MenuChoice
  2.     {
  3.     [CmdletBinding ()]
  4.     Param
  5.         (
  6.         [Parameter (
  7.             Mandatory,
  8.             Position = 0
  9.             )]
  10.             [string[]]
  11.             $MenuList,
  12.  
  13.         [Parameter (
  14.             Position = 1
  15.             )]
  16.             [string]
  17.             $Title,
  18.  
  19.         [Parameter (
  20.             Position = 2
  21.             )]
  22.             [string]
  23.             $Prompt = 'Please enter a number from the above list or "x" to exit '
  24.            
  25.         )
  26.  
  27.     $ValidChoices = 0..$MenuList.GetUpperBound(0) + 'x'
  28.     $Choice = ''
  29.     while ([string]::IsNullOrEmpty($Choice))
  30.         {
  31.         Write-Host $Title
  32.         foreach ($Index in 0..$MenuList.GetUpperBound(0))
  33.             {
  34.             Write-Host ('{0} - {1}' -f $Index, $MenuList[$Index])
  35.             }
  36.         $Choice = Read-Host -Prompt $Prompt
  37.         Write-Host ''
  38.  
  39.         if ($Choice -notin $ValidChoices)
  40.             {
  41.             [System.Console]::Beep(1000, 300)
  42.             Write-Warning ''
  43.             Write-Warning ('    [ {0} ] is not a valid selection.' -f $Choice)
  44.             Write-Warning '    Please try again.'
  45.             Write-Warning ''
  46.  
  47.             $Choice = ''
  48.  
  49.             pause
  50.             }
  51.         }
  52.  
  53.     # send it out to the caller
  54.     if ($Choice -eq 'x')
  55.         {
  56.         'Exit'
  57.         }
  58.         else
  59.         {
  60.         $Choice
  61.         }
  62.     } # end >>> function Get-MenuChoice
  63.  
  64.  
  65. '***** demo usage below *****'
  66.  
  67. $MenuList = @(
  68.     'An Item'
  69.     'Some Other Item'
  70.     'Middle Menu Item'
  71.     'Yet Another Item'
  72.     'The Last Choice'
  73.     )
  74.  
  75. $Choice = Get-MenuChoice -MenuList $MenuList
  76.  
  77. 'You chose [ {0} ] giving you [ {1} ].' -f $Choice, $MenuList[$Choice]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement