Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Created August 11, 2017 14:50
Show Gist options
  • Save indented-automation/8701e3d571edb1ea6d8abe28c08ec831 to your computer and use it in GitHub Desktop.
Save indented-automation/8701e3d571edb1ea6d8abe28c08ec831 to your computer and use it in GitHub Desktop.
New-ConsoleMenu
function New-ConsoleMenu {
param (
[ScriptBlock]$ScriptBlock,
[String]$Title,
[String]$Prompt,
[Object]$Default,
[String]$Property
)
Clear-Host
$items = & $ScriptBlock
for ($i = 0; $i -lt $menuPadding - 2; $i++) {
Write-Host
}
Write-Host
Write-Host (' {0}' -f $Title) -ForegroundColor Cyan
Write-Host
$padding = switch (@($items).Count) {
{ $_ -lt 10 } { 3; break }
{ $_ -lt 100 } { 4; break }
{ $_ -lt 1000 } { 5; break }
default { 2 }
}
for ($i = 1; $i -le $items.Count; $i++) {
Write-Host ' ' -NoNewLine
if ($psboundparameters.ContainsKey('Default') -and $i -eq $Default) {
$foregroundColor = 'Yellow'
} else {
$foregroundColor = 'White'
}
Write-Host ('{0}.' -f $i).ToString().PadRight($padding) -ForegroundColor $foregroundColor -NoNewLine
Write-Host $items[$i - 1].$Property
}
for ($j = $i; $j -lt $host.UI.RawUI.WindowSize.Height - 3; $j++) {
Write-Host
}
Write-Host $prompt -NoNewLine
if ($psboundparameters.ContainsKey('Default')) {
Write-Host (' [Default: {0}]' -f $Default) -ForegroundColor Yellow -NoNewLine
}
$itemNumber = Read-Host ' '
if (-not $itemNumber -and $psboundparameters.ContainsKey('Default')) {
$items[$Default - 1]
} elseif ($null -ne $itemNumber) {
$items[[Int]$itemNumber - 1]
} else {
New-ConsoleMenu $psboundparameters
}
}
@asheroto
Copy link

Is this the best way to create the prompts?

$items = @(
    [PSCustomObject]@{ Name = "Option 1" }
    [PSCustomObject]@{ Name = "Option 2" }
    [PSCustomObject]@{ Name = "Option 3" }
)

New-ConsoleMenu -ScriptBlock { $items } -Title "Main Menu" -Prompt "Please select an option:" -Property "Name"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment