RosettaCodeData/Task/Menu/PowerShell/menu.psh

78 lines
2.2 KiB
Text
Raw Permalink Normal View History

2016-12-05 22:15:40 +01:00
function Select-TextItem
{
<#
.SYNOPSIS
Prints a textual menu formatted as an index value followed by its corresponding string for each object in the list.
.DESCRIPTION
Prints a textual menu formatted as an index value followed by its corresponding string for each object in the list;
Prompts the user to enter a number;
Returns an object corresponding to the selected index number.
.PARAMETER InputObject
An array of objects.
.PARAMETER Prompt
The menu prompt string.
.EXAMPLE
“fee fie”, “huff and puff”, “mirror mirror”, “tick tock” | Select-TextItem
.EXAMPLE
“huff and puff”, “fee fie”, “tick tock”, “mirror mirror” | Sort-Object | Select-TextItem -Prompt "Select a string"
.EXAMPLE
Select-TextItem -InputObject (Get-Process)
.EXAMPLE
(Get-Process | Where-Object {$_.Name -match "notepad"}) | Select-TextItem -Prompt "Select a Process" | Stop-Process -ErrorAction SilentlyContinue
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true)]
$InputObject,
[Parameter(Mandatory=$false)]
[string]
$Prompt = "Enter Selection"
)
Begin
{
$menuOptions = @()
}
Process
{
$menuOptions += $InputObject
}
End
{
2020-02-17 23:21:07 -08:00
if(!$inputObject){
return ""
}
2016-12-05 22:15:40 +01:00
do
{
[int]$optionNumber = 1
foreach ($option in $menuOptions)
{
Write-Host ("{0,3}: {1}" -f $optionNumber,$option)
$optionNumber++
}
Write-Host ("{0,3}: {1}" -f 0,"To cancel")
2020-02-17 23:21:07 -08:00
$choice = Read-Host $Prompt
2016-12-05 22:15:40 +01:00
$selectedValue = ""
if ($choice -gt 0 -and $choice -le $menuOptions.Count)
{
$selectedValue = $menuOptions[$choice - 1]
}
2020-02-17 23:21:07 -08:00
2016-12-05 22:15:40 +01:00
}
2020-02-17 23:21:07 -08:00
until ($choice -match "^[0-9]+$" -and ($choice -eq 0 -or $choice -le $menuOptions.Count))
2016-12-05 22:15:40 +01:00
return $selectedValue
}
}
“fee fie”, “huff and puff”, “mirror mirror”, “tick tock” | Select-TextItem -Prompt "Select a string"