PS: History 🚧
In this post, we’ll take a look at command history in PowerShell.
PowerShell by default saves 4096 (2¹²) of the last commands executed in global history, and is accessible using (Get-PSReadlineOption).HistorySavePath
. To increase this number, use the -MaximumHistoryCount
option:
Set-PSReadlineOption -MaximumHistoryCount 10000
Local History (Current Session)
The common history cmdlets are:
PS> man *-history | fl
Name Category Module Synopsis
---- -------- ------ --------
Add-History Cmdlet Microsoft.PowerShell.Core Appends entries to the session history.
Clear-History Cmdlet Microsoft.PowerShell.Core Deletes entries from the PowerShell session command history.
Get-History Cmdlet Microsoft.PowerShell.Core Gets a list of the commands entered during the current session.
Invoke-History Cmdlet Microsoft.PowerShell.Core Runs commands from the session history.
Note that these are limited to the current session only.
When working with history, you’d mostly like to re-run some commands. You can do this with the Up/Down arrow keys. (In Vi-mode, use j/k in Command-mode).
Above history cmdlets are useful when:
- You’ve had a long session, and it’s easier to lookup the whole command-history rather than iterate through each issued command.
- You’ve had a long session, and want to maintain a record of all issued commands.
- You’ve had a long session, and want to import all these commands into a new session.
- You want to do something with your command history, like lookup when a certain command was issued, how long it ran for, etc.
The next obvious thing is to see how to export/import your session history.
Export/Import History
You can export/import command-history to/from an XML file.
Get-History | Export-CliXml $HOME/cmd-history.xml
Add-History (Import-CliXml $HOME/cmd-history.xml)
In addition to the Up/Down arrow keys, you can access history using keywords. This is the classic Find Backward/Forward option, accessible using Ctrl+R
by default. Since these shortcuts are handled by PSReadLine, it’s best to check for all history-related keybindings that PSReadLine currently offers:
Get-PSReadLineKeyHandler | where {$_.Function -like '*hist*'}
With Vi-Mode enabled, instead of Ctrl+R
you can use /cmdlet
to lookup past commands issued with the keyword “cmdlet” in them (Use n/N to navigate the list like you would in Vim).