Skip to content

Instantly share code, notes, and snippets.

@davehague
Created September 19, 2024 18:24
Show Gist options
  • Save davehague/d3f8e20a335fcd878d8148f5fa3e3716 to your computer and use it in GitHub Desktop.
Save davehague/d3f8e20a335fcd878d8148f5fa3e3716 to your computer and use it in GitHub Desktop.
Powershell version of Linux's `history` command

Wouldn't it be nice if Powershell could simulate history | grep "alembic"? Now it can.

Place this in your Powershell profile (PS> $PROFILE to find the path)

function Get-CommandHistory {
    param (
        [string]$Pattern = "*"
    )

    # Define the path to the command history file
    $historyFile = "$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt"
    
    # Use a HashSet to track unique commands while preserving order
    $hashset = New-Object System.Collections.Generic.HashSet[string]

    # Read the history file and filter commands based on the pattern
    Select-String -Path $historyFile -Pattern $Pattern | 
    ForEach-Object { 
        if ($_.Line -and !$hashset.Contains($_.Line)) {
            $hashset.Add($_.Line) | Out-Null
            $_.Line
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment