Your basic ITPro blog... What's going on at work, what I'm interested in.

Wednesday, March 4, 2009

Powershell – Preserving history for future sessions

Typing ‘exit’ in a Powershell console, as you would imagine, exits the console. I use PowerShellPlus almost exclusively (and love it!). Typing ‘exit’ while in PowerShellPlus (known affectionately as simply “teh+”) gives you the option of closing the app or starting a new, clean console session. I often use this as a quick way to clean out my console environment.

I have also written a small function, named ‘exitt’, that exits AFTER securing the console. I sign all of my scripts. But sometimes, while working on something, I will set my Execution Policy to ‘remotesigned’ for a while. But, I pretty much always set my Execution Policy to ‘allsigned’ before exiting. That way, nothing unsigned by myself will accidentally (or maliciously… am I paranoid?) run the next time I start Powershell.

Anyway, back to my point…

When I type ‘exit’ or run my ‘exitt’ function and stay in teh+, my history is wiped out. This usually isn’t a problem. But, there are times when I want a clean, fresh console AND my history. To that end, I tweaked my ‘exitt’ function and my profile a bit.

(NOTE: I did this before really researching things on the Internet. There are probably better ways of handling this, but this works for me).

The meat of my ‘exitt’ function looks like this:

  1. param  
  2. (  
  3.     [Parameter(Position=0, Mandatory=$false, ValueFromPipeLine=$false)] 
  4.         [switch]$history = $false 
  5.  
  6. # Call Secure-Console function to set executionPolicy to AllSigned 
  7. Secure-Console 
  8.  
  9. # If switched, export history for future use. Otherwise, blow out history 
  10. if ($history
  11.     Get-History | Export-Clixml "c:\scripts\hist.xml" -Force 
  12. else 
  13.     Remove-Item "c:\scripts\hist.xml" -Force -ea SilentlyContinue 
  14.  
  15. #Close Program 
  16. exit 

So, if I run the function with the –history switch, it writes the current history out to an XML file.

Then, my profile has this bit:

  1. if (Test-Path "c:\scripts\hist.xml"
  2.     Add-History (Import-Clixml "c:\scripts\hist.xml"
  3.     Remove-Item "c:\scripts\hist.xml" -Force -ea SilentlyContinue 

Pretty simple, and it works for me.

After writing this, I did a quick search in the ‘tubes and came across JSnover’s solution to this. Maybe I will do that first next time. 

:-)

No comments:

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332