Friday, November 6, 2015

Persistent Command History in PowerShell

If you are familiar with .bash_history or just wish you had a history of your powershell commands persist between sessions here is a handy little script. It will persist command history when you exit a powershell session to a file in %USERPROFILE% called .ps_history.

Copy the code below and save to a file called “Microsoft.PowerShell_profile.ps1” and save it in “%USERPROFILE%\Documents\WindowsPowerShell”

$HistoryFilePath = Join-Path -Path ([Environment]::GetFolderPath('UserProfile')) -ChildPath ".ps_history"; 
function Persist-History {
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {
Get-History | Select-Object -Unique | Export-Clixml -Path $HistoryFilePath;
} | Out-Null;
if (Test-path -Path $HistoryFilePath) {
Import-Clixml -Path $HistoryFilePath | Add-History;
}
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward;
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward;
}
Persist-History;
 

Disclaimer: I have only tested this with PowerShell 5


If it doesn’t work, you could probably make it work by installing the PackageManagement modules for PowerShell and install the “PSReadline” module.

Persistent Command History in PowerShell

If you are familiar with .bash_history or just wish you had a history of your powershell commands persist between sessions here is a handy little script. It will persist command history when you exit a powershell session to a file in %USERPROFILE% called .ps_history.

Copy the code below and save to a file called “Microsoft.PowerShell_profile.ps1” and save it in “%USERPROFILE%\Documents\WindowsPowerShell”

$HistoryFilePath = Join-Path -Path ([Environment]::GetFolderPath('UserProfile')) -ChildPath ".ps_history"; 
function Persist-History {
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {
Get-History | Select-Object -Unique | Export-Clixml -Path $HistoryFilePath;
} | Out-Null;
if (Test-path -Path $HistoryFilePath) {
Import-Clixml -Path $HistoryFilePath | Add-History;
}
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward;
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward;
}
Persist-History;
 

Disclaimer: I have only tested this with PowerShell 5


If it doesn’t work, you could probably make it work by installing the PackageManagement modules for PowerShell and install the “PSReadline” module.