Skip to content

Instantly share code, notes, and snippets.

@TangentFoxy
Created September 7, 2017 04:42
Show Gist options
  • Save TangentFoxy/86f4c3b94974c028d6d9d828542d5ca0 to your computer and use it in GitHub Desktop.
Save TangentFoxy/86f4c3b94974c028d6d9d828542d5ca0 to your computer and use it in GitHub Desktop.
Making PowerShell history persist between sessions.
# Usage: run this file, it will install itself
# to $profile and be run from there
# Make sure $profile exists.
if (! (Test-Path $profile) ) {
New-Item -Path $profile -ItemType File -Force
}
# Find ourselves and where we should be.
$me = $PSCommandPath # $MyInvocation.MyCommand.Definition
$destiny = $(Resolve-Path '~\Documents\WindowsPowerShell').ToString() + "\persist_history.ps1"
# Install script if needed.
if (! ($me -eq $destiny) ) {
# Copy ourselves.
Copy-Item $me $destiny
# Append calling this script to $profile.
Add-Content $profile "`nInvoke-Expression -Command $destiny"
}
# Save history on exit.
Register-EngineEvent PowerShell.Exiting -Action {
Get-History -Count 4KB | Export-CSV ~\Documents\WindowsPowerShell\powershell_history.csv
} > $null # silence output
# Load previous history if it exists.
if (Test-Path ~\Documents\WindowsPowerShell\powershell_history.csv) {
Import-CSV ~\Documents\WindowsPowerShell\powershell_history.csv | Add-History
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment