Quickly Search Your Entire PowerShell Command History (Even Across Sessions)
20 Feb 2026
Here’s a tiny, powerful one-liner function I added to my $PROFILE that makes searching the real history (all past sessions) almost as easy as history | grep on Linux.
The Function: hgrep
function hgrep {
param([string]$Pattern)
Get-Content (Get-PSReadLineOption).HistorySavePath |
Select-String $Pattern |
Select-Object -ExpandProperty Line -Unique
}
That’s it. Four lines.
How to use it
hgrep git # shows every git command you ever ran
hgrep "docker build" # exact phrase search
hgrep error # find commands that produced errors (if you included error text)
hgrep azure # rediscover that one az cli command you used six months ago
The -Unique makes sure you don’t see the same command repeated 20 times if you ran it a lot.
Why this works (and why Get-History isn’t enough)
Get-History-> current session only(Get-PSReadLineOption).HistorySavePath-> the real persistent file PowerShell has been quietly writing to (usually something like~\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt)
Bonus: Even faster daily workflow
While this function is great for terminal scripts or when you want to pipe/grep further, for everyday use many people (myself included) just rely on:
Ctrl + R
- starts reverse-i-search across all saved history
- type a few letters -> keep pressing Ctrl + R to cycle through matches
It’s usually faster than typing hgrep, but when you want to see multiple matches at once or copy-paste several similar commands, hgrep wins.
Making it permanent
- Open your profile:
notepad $PROFILE(If it doesn’t exist yet, PowerShell will create it when you save.)
-
Paste the function at the bottom.
- Save and either:
- Restart PowerShell, or
- Run
. $PROFILEto reload immediately
You can also rename it to something shorter like hg if you type it 50 times a day:
function hg { param([string]$Pattern) ... } # same body
Optional tiny upgrade (if you want)
If you find yourself searching very frequently and the history file has grown huge (tens of thousands of lines), you can limit it to the most recent entries for speed:
function hgrep {
param([string]$Pattern)
Get-Content (Get-PSReadLineOption).HistorySavePath -Tail 15000 |
Select-String $Pattern |
Select-Object -ExpandProperty Line -Unique
}
-Tail 15000 ≈ last ~15,000 commands — usually more than enough.
Final thought
PowerShell’s persistent history is good but it hides the good stuff.
With this five-line function you get Linux-style history | grep behavior without installing anything extra.
Happy command-line archeology! 🕵️♂️