RosettaCodeData/Task/Menu/PowerShell/menu.psh

78 lines
2.2 KiB
Plaintext

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
{
if(!$inputObject){
return ""
}
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")
$choice = Read-Host $Prompt
$selectedValue = ""
if ($choice -gt 0 -and $choice -le $menuOptions.Count)
{
$selectedValue = $menuOptions[$choice - 1]
}
}
until ($choice -match "^[0-9]+$" -and ($choice -eq 0 -or $choice -le $menuOptions.Count))
return $selectedValue
}
}
“fee fie”, “huff and puff”, “mirror mirror”, “tick tock” | Select-TextItem -Prompt "Select a string"