Skip to content

Instantly share code, notes, and snippets.

@SteveL-MSFT
Last active February 23, 2021 00:06
Show Gist options
  • Save SteveL-MSFT/3a0dbb33ee725aaeddc362ca3cac0ec3 to your computer and use it in GitHub Desktop.
Save SteveL-MSFT/3a0dbb33ee725aaeddc362ca3cac0ec3 to your computer and use it in GitHub Desktop.
$parameters = @{
Key = 'F7'
BriefDescription = 'ShowMatchingHistoryOcgv'
LongDescription = 'Show Matching History using Out-ConsoleGridView'
ScriptBlock = {
param($key, $arg) # The arguments are ignored in this example
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
$history = [Microsoft.PowerShell.PSConsoleReadLine]::GetHistoryItems().CommandLine | Select-Object -Unique
# reverse the items so most recent is on top
[array]::Reverse($history)
$selection = $history | Out-ConsoleGridView -Title "Select 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)
}
}
}
Set-PSReadLineKeyHandler @parameters
@tig
Copy link

tig commented Sep 27, 2020

Steve, I found that using [Microsoft.PowerShell.PSConsoleReadLine]::GetHistoryItems() is super slow compared to using Get-History -Count 500 | Sort-Object -Descending -Property Id.

@SteveL-MSFT
Copy link
Author

@tig Get-History will only show you what is from the current session while the PSReadLine one is a history across all PowerShell sessions

@tig
Copy link

tig commented Sep 27, 2020

@tig Get-History will only show you what is from the current session while the PSReadLine one is a history across all PowerShell sessions

Ahhh. Any way to make the PSReadLine quicker?

@tig
Copy link

tig commented Sep 28, 2020

doing the [array]::Reverse($history) after you Select-Object -Unique means that more recent duplicates are removed.

See my latest here for a solution that:

a) Supports both searching current PowerShell Instance (F7) and Global (Shift-F7)
b) Removes duplicates after sort
c) Leverages ocgv -Filter instead of adding another filter mechanism with Where-Object -like

I'm still learning PS, so I have a feeling there's a better way to package all this, but it works for now.

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