Using Get-History
cmdlet #
- Get-Command History: Use
Get-History
in PowerShell to view your session’s command history
- Retrieve Command by ID: You can re-run a command by its history ID:
Invoke-History -Id <ID>
- Exporting Command History: Save the command history to a file for future reference.
Get-History | Export-Csv -Path "C:\path\to\history.csv" -NoTypeInformation
Using h
alias #
- The
Get-History
cmdlet has a short alias,h
, that you can use as a shorthand: h
Permanent Command History Across Sessions #
PowerShell does not persist command history by default across sessions. However, using the PSReadLine module (available in PowerShell 5.1+), you can enable persistent history.
- Enable PSReadLine Module: Ensure it’s installed and loaded.
Install-Module -Name PSReadLine
Import-Module PSReadLine - View Persistent History:
Get-Content (Get-PSReadlineOption).HistorySavePath
Viewing Command History from Previous Sessions #
PowerShell saves command history across sessions in a file. You can open this file to view your past commands. The default location for this file is:
- Windows PowerShell:
C:\Users\<YourUserName>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
- PowerShell (Core):
C:\Users\<YourUserName>\AppData\Roaming\Microsoft\PowerShell\PSReadLine\ConsoleHost_history.txt
You can open this file in any text editor or view its contents using PowerShell:
Get-Content "$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt"
Or for PowerShell Core:
Get-Content "$env:APPDATA\Microsoft\PowerShell\PSReadLine\ConsoleHost_history.txt"
This allows you to view a persistent history across multiple sessions.
Clear Command History #
- Clear PowerShell History for Current Session:
Clear-History
- Delete Persistent PowerShell History: Locate the history file and delete or clear it:
Remove-Item (Get-PSReadlineOption).HistorySavePath