How to search Powershell command history from previous sessions

Solution 1:

The persistent history you mention is provided by PSReadLine. It is separate from the session-bound Get-History.

The history is stored in a file defined by the property (Get-PSReadlineOption).HistorySavePath. View this file with Get-Content (Get-PSReadlineOption).HistorySavePath, or a text editor, etc. Inspect related options with Get-PSReadlineOption. PSReadLine also performs history searches via ctrl+r.

Using your provided example:

Get-Content (Get-PSReadlineOption).HistorySavePath | ? { $_ -like '*docker cp*' }

Solution 2:

  • Press Ctrl+R and then start typing, to search backward in history interactively. This matches the text from anywhere in the command line. Press Ctrl+R again to find next match.
  • Ctrl+S works like above, but searches forward in history. You can use Ctrl+R/Ctrl+S to go back and forth in search results.
  • Type a text and then press F8. This searches for the previous item in the history that starts with the current input.
  • Shift+F8 works like F8, but searches forward.

More Info

As @jscott mentioned in his/her answer, PowerShell 5.1 or higher in Windows 10, uses the PSReadLine module to support command editing environment. The full key mapping of this module can be retrieved by using Get-PSReadLineKeyHandler cmdlet. To view all the key mappings related to history, use the following command:

Get-PSReadlineKeyHandler | ? {$_.function -like '*hist*'}

and here is the output:

History functions
=================
Key       Function              Description
---       --------              -----------
Alt+F7    ClearHistory          Remove all items from the command line history (not PowerShell history)
Ctrl+s    ForwardSearchHistory  Search history forward interactively
F8        HistorySearchBackward Search for the previous item in the history that starts with the current input - like
                                PreviousHistory if the input is empty
Shift+F8  HistorySearchForward  Search for the next item in the history that starts with the current input - like
                                NextHistory if the input is empty
DownArrow NextHistory           Replace the input with the next item in the history
UpArrow   PreviousHistory       Replace the input with the previous item in the history
Ctrl+r    ReverseSearchHistory  Search history backwards interactively

Solution 3:

I have this in my PS profile:

function hist { $find = $args; Write-Host "Finding in full history using {`$_ -like `"*$find*`"}"; Get-Content (Get-PSReadlineOption).HistorySavePath | ? {$_ -like "*$find*"} | Get-Unique | more }