Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Get-MenuChoice
- {
- #region Comment Based Help [CBH]
- <#
- .SYNOPSIS
- Display a text menu & returns a valid response.
- #>
- #endregion
- #region Parameters
- # For some unknown reason, parameter help comments will not work without a CBH.
- [CmdletBinding()]
- Param
- (
- # Required string or string array of menu item[s] to display.
- [Parameter(
- Mandatory,
- Position = 0
- )]
- [ValidateNotNullOrEmpty()]
- [string[]]
- $MenuItems,
- # Optional menu title.
- [Parameter(
- Position = 1
- )]
- [string]
- $MenuTitle = '',
- # Optional user prompt.
- [Parameter(
- Position = 2
- )]
- [string]
- $MenuPrompt = 'Please enter a choice from the above items '
- )
- #endregion
- #region Init variables
- $ValidMenuChoices = $MenuItems | ForEach-Object {$_[0]}
- $Frequency = 1000
- $Duration = 100
- $MenuChoice = ''
- #endregion
- while ($MenuChoice -notin $ValidMenuChoices)
- {
- Clear-Host
- if (-not [string]::IsNullOrEmpty($MenuTitle))
- {
- $MenuTitle | Out-Host
- }
- $MenuItems | Out-Host
- Write-host ''
- $MenuChoice = (Read-Host $MenuPrompt).ToLower()
- if ($MenuChoice -notin $ValidMenuChoices)
- {
- # The bell char doesn't work in the ISE and [console]:: items
- # don't work in non-interactive sessions.
- if ($Host.Name -match 'ISE')
- {
- [console]::Beep($Frequency, $Duration)
- }
- else
- {
- Write-Host [char]7
- }
- }
- }
- return $MenuChoice
- } # end function Get-MenuChoice
- #region Testing section - comment out or remove when finished
- $TopMenu = (
- '1 - First item',
- '2 - Second choice',
- '3 - Third selection',
- 'x - Exit')
- #$Choice = Get-MenuChoice $TopMenu
- $Choice = Get-MenuChoice -MenuItems $TopMenu -MenuTitle 'Custom menu title' -MenuPrompt 'Custom menu prompt '
- Write-Output ''
- switch ($Choice)
- {
- '1' {Write-Output "Do the first thing."; break}
- '2' {Write-Output "The 2nd thing must be done."; break}
- '3' {Write-Output "Three is the number of the thing to do."; break}
- 'x' {Write-Output "Exit now."; break}
- }
- #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement