PowerShell, Scripting
comments 2

Archiving PowerShell command history on a daily basis

I try quite a few things everyday within in a PowerShell prompt or ISE or some other script editor. Sometimes, there will be some useful one-liners I receive on Twitter or found somewhere on Internet. However, once I close the session, the whole command history is gone and I lose all that I tried if I don’t save that in a seperate file. Remembering to save everything I type at command console can be quite painful. In fact, yesterday, I was searching for a tweet I received just a few days ago. To my horror, it was not there on Twitter time line also. So, I decided to write something to save all the command history when I exit the console or my favorite PowerShell editor.  

I quickly searched on the net and found @oising‘s persisting command history post which uses eventing to save the command history to a file before exiting. This is what I needed. But as I started using it, I realized the limitations.  

  1. The command history is always saved to the same file and only last 100 commands will be available.
  2. Within that last 100 commands, there were lot of duplicates.
  3. With 1 & 2, I won’t achieve what I need — looking back in to the “real” history.

So, I decided (again.!) to write something my own and this time I really did that. So, here is what I have.  

 You can just dump this in to your PowerShell profile. This is what happens when you open PowerShell console with this profile 

  1. Construct a history.clixml file name with today’s date embedded in to the file name.
  2. Check if that file exists and import all the old command history in to the current session.
  3. At the exit event, Use Export-History function to export command history from the current session back in to the file. Also, remove all duplicates while exporting.
This command history archival happens on a daily basis. So, all the commands you tried at the console in a day will all be available in the same history file. Other functions supported are
 
Get-HistoryArchives
Lists all the available archive files.
 
Show-HistoryArchive
Shows the contents of an achive file.
 
Export-History $path
Export the current session history in to different file.
 
Import-History $path
Import history from  file in to a current session.
 
This is it. Hope this helps..!
Filed under: PowerShell, Scripting

by

Ravikanth is a principal engineer and the lead architect for Microsoft and VMware virtualized and hybrid cloud solutions within the Infrastructure Solutions Group at Dell EMC. He is a multi-year recipient of Microsoft Most Valuable Professional (MVP) award in Windows PowerShell (CDM) and Microsoft Azure. Ravikanth is the author of Windows PowerShell Desired State Configuration Revealed (Apress) and leads Bangalore PowerShell and Bangalore IT Pro user groups. He can be seen speaking regularly at local user group events and conferences in India and abroad.