Perserving Command History Across Sessions

PowerShell Team

<Edited 7/2/2006 to add tags and Categories>

Ben Winzenz didn’t like the fact that Windows PowerShell did not maintain history lists between sessions (http://winzenz.blogspot.com/2006/06/cool-mshpowershell-tidbit.html) .   We hear you Ben.  Back to my least favorite phrase, “to ship is to choose”.  That said, we try to give you in the community the power to do that which we cannot.  Here is some code that you can put in your profile file that defines a function BYE which saves off your sessions history into a History.CSV file in your home directory and then adds that to your history when you startup the next session.  You get to control how much of the history you want (up to 32KB-1) but I just do 1KBs worth.

$MaximumHistoryCount = 1KB

if (!(Test-Path ~\PowerShell -PathType Container))
{   New-Item ~\PowerShell -ItemType Directory
}

function bye
{   Get-History -Count 1KB |Export-CSV ~\PowerShell\history.csv
    exit
}

if (Test-path ~\PowerShell\History.csv)
{   Import-CSV ~\PowerShell\History.csv |Add-History
}

I was going to put comments in the code but thought I would test out my assertion that VERBOSITY produces self-documenting scripts.  I think it does but you can let me know one way or the other.

So add this to your startup and then do a session, type BYE instead of EXIT and then start a new session and do a Get-History.   You’ll see a bunch of commands already in your list. 

Now lets have a little fun with History, do what I instructed above and get into your new session.  Now do a Get-History and pipe it to Get-Member:

PS> Get-History |Get-Member -MemberType Property
   TypeName: Microsoft.PowerShell.Commands.HistoryInfo

Name               MemberType Definition
—-               ———- ———-
CommandLine        Property   System.String CommandLine {get;}
EndExecutionTime   Property   System.DateTime EndExecutionTime {get;}
ExecutionStatus    Property   System.Management.Automation.Runspaces.Pip…
Id                 Property   System.Int64 Id {get;}
StartExecutionTime Property   System.DateTime StartExecutionTime {get;}

This means that you can find out when something was executed (e.g. which session it happened in) using the following command:

PS> ghy |ft id,endexecutiontime,commandline -auto

 Id EndExecutionTime      CommandLine
 — —————-      ———–
612 6/29/2006 5:39:34 AM  gcm export-csv |fl *
613 6/30/2006 6:51:16 PM  ipconfig
614 6/30/2006 8:51:38 PM  cd C:\kits

Enjoy!
Jeffrey P. Snover
Windows PowerShell Architect

PSMDTAG:FAQ: How do I perserve command history across sessions?

PSMDTAG:FAQ:  Can I run an exit script?

PSMDTAG:ENVIRONMENT: History

PSMDTAG:SHELL: shutdown, startup, exitScript

0 comments

Discussion is closed.

Feedback usabilla icon