Skip to content

Instantly share code, notes, and snippets.

@pitermarx
Created August 28, 2024 13:28
Show Gist options
  • Save pitermarx/076e1c68bb23a77b5a8aa19ef1abce29 to your computer and use it in GitHub Desktop.
Save pitermarx/076e1c68bb23a77b5a8aa19ef1abce29 to your computer and use it in GitHub Desktop.
A powershell menu
function menu($items, $HighlightColor = "Yellow", [Switch]$ReturnIndex, [Switch]$MultiSelect) {
$selected=@()
:w while ($true) {
# prevent overflow
$pos = if ($null -eq $pos -or $pos -lt 0) { 0 } else { [Math]::Min($pos, $items.Length-1) }
# draw
$i=0
$items | ForEach-Object {
$x = if (-not $MultiSelect) { "" } elseif ($selected -contains $i) { " [x]" } else { " [ ]" }
if ($i++ -eq $pos) { Write-Host ">$x $_" -ForegroundColor $HighlightColor }
else { Write-Host " $x $_" }
}
# move
switch ($host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown").VirtualKeyCode) {
27 { return $null } #escape
{ 38,75 -eq $_ } { $pos-- } #down,j
{ 40,74 -eq $_ } { $pos++ } #up,k
{ 13,32 -eq $_ } { #space,enter
if (-not $MultiSelect -or 32 -eq $_) {
$selected =
if ($selected -contains $pos) { $selected | Where-Object { $_ -ne $pos } }
else { @($selected) + @($pos) }
}
if (-not $MultiSelect -or 13 -eq $_) { break w }
}
}
# go to top
[System.Console]::SetCursorPosition(0, [System.Console]::CursorTop - $items.Length)
}
return $(if ($ReturnIndex) { $selected } else { $items[$selected] })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment