Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
$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

This comment has been minimized.

Copy link

@tig tig commented Sep 27, 2020

See my updated version here which takes advantage of the new -Filter option for ocgv and preserves cursor location.

https://gist.github.com/tig/cbbeab7f53efd73e329afd6d4b838191

@tig

This comment has been minimized.

Copy link

@tig 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

This comment has been minimized.

Copy link
Owner Author

@SteveL-MSFT SteveL-MSFT 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

@tig

This comment has been minimized.

Copy link

@tig 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

This comment has been minimized.

Copy link

@tig 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