Skip to content

Instantly share code, notes, and snippets.

@stephenbaidu
Last active March 16, 2022 09:30
Show Gist options
  • Save stephenbaidu/21bab143af09d51afc641f8e6206ec3a to your computer and use it in GitHub Desktop.
Save stephenbaidu/21bab143af09d51afc641f8e6206ec3a to your computer and use it in GitHub Desktop.
Function SimpleContextMenu {
param (
[Parameter(Mandatory, Position = 0)]
[System.Object]
$List,
[Parameter(Mandatory = $false, Position = 1)]
[string]
$Header = "Select"
)
if (@("OrderedDictionary", "Hashtable", "Object[]") -notcontains $List.GetType().Name) {
Write-Host "Collection type not supported"
return
}
$choices = @{}
[Int32]$lastIndex = 0
Write-Host $Header -ForegroundColor Blue
if ($List.GetType().IsArray) {
foreach ($item in $List) {
$choices[++$lastIndex] = $item
Write-Host " $($lastIndex): $item"
}
}
else {
foreach ($item in $List.GetEnumerator()) {
if ($item.Name.StartsWith("__")) {
# Keys with this prefix are treated as information and are good for headers and separators
Write-Host "$($item.Value)" -ForegroundColor Blue
}
else {
$choices[++$lastIndex] = $item.Name
Write-Host " $($lastIndex): $($item.Value)"
}
}
}
[Int32]$choice = SimpleInputPrompt "Enter a number between [1, $lastIndex] to select command or <Enter> to ignore"
if (($choice -gt 0) -and ($choice -le $lastIndex)) {
return $choices[$choice]
}
else {
return $null
}
}
Function SimpleInputPrompt {
param (
[Parameter(Mandatory = $false, Position = 0)]
[string]
$Label = "Provide Input"
)
Write-Host ""
Write-Host $Label -ForegroundColor Blue
return Read-Host
}
Function IsPortListening {
param (
[Parameter(Mandatory = $true, Position = 0)]
[int]
$Port
)
$test = Test-NetConnection localhost -port $Port
return $test.TcpTestSucceeded
}
Function KillProcessOnPort {
param (
[Parameter(Mandatory = $true, Position = 0)]
[int]
$Port
)
$foundProcesses = netstat -ano | findstr :$Port
$activePortPattern = ":$Port\s.+LISTENING\s+\d+$"
$pidNumberPattern = "\d+$"
if ($foundProcesses | Select-String -Pattern $activePortPattern -Quiet) {
$patternMatches = $foundProcesses | Select-String -Pattern $activePortPattern
$firstMatch = $patternMatches.Matches.Get(0).Value
$pidNumber = [regex]::match($firstMatch, $pidNumberPattern).Value
taskkill /pid $pidNumber /f
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment