Skip to content

Instantly share code, notes, and snippets.

@tig
Last active Aug 9, 2021
Embed
What would you like to do?
Use F7 as "Show Command History" in Powershell

Use F7 as "Show Command History" in Powershell

Setup

Requires Out-ConsoleGridView from GraphicalTools.

  1. Install GraphicalTools by typing the command Install-Module -Name Microsoft.PowerShell.ConsoleGuiTools
  2. Run the F7History.ps1 script below (optionally, run from $profile so it's always ready).

Usage

Press F7 to see the history for the current PowerShell instance

Press Shift-F7 to see the history for all PowerShell instances.

Whatever is selected within Out-ConsoleGridView will be inserted on the command line when ENTER is pressed.

Whatever was typed on the command line prior to hitting F7 or Shift-F7 will be used as a filter for ocgv.

function ocgv_history {
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
$selection = $input | Out-ConsoleGridView -Title "Select CommandLine from History" -OutputMode Single -Filter $line
if ($selection) {
[Microsoft.PowerShell.PSConsoleReadLine]::DeleteLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($selection)
if ($selection.StartsWith($line)) {
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor)
}
else {
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($selection.Length)
}
}
}
$parameters = @{
Key = 'F7'
BriefDescription = 'ShowMatchingHistoryOcgv'
LongDescription = 'Show Matching History using Out-ConsoleGridView'
ScriptBlock = {
param($key, $arg) # The arguments are ignored in this example
Get-History | Sort-Object -Descending -Property Id -Unique | Select-Object CommandLine -ExpandProperty CommandLine | ocgv_history
}
}
Set-PSReadLineKeyHandler @parameters
$parameters = @{
Key = 'Shift-F7'
BriefDescription = 'ShowMatchingGlobalHistoryOcgv'
LongDescription = 'Show Matching History for all PowerShell instances using Out-ConsoleGridView'
ScriptBlock = {
param($key, $arg) # The arguments are ignored in this example
$hist = [Microsoft.PowerShell.PSConsoleReadLine]::GetHistoryItems().CommandLine
# reverse the items so most recent is on top
[array]::Reverse($hist)
$hist | Select-Object -Unique -First 1000 | ocgv_history
}
}
Set-PSReadLineKeyHandler @parameters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment