+8  A: 

Get-Unique also requires a sorted list and I assume you probably want to preserve execution order. Try this instead:

Get-History -Count 32767 | Group CommandLine | Foreach {$_.Group[0]} | 
Export-Clixml "$home\pshist.xml"

This approach uses the Group-Object cmdlet to create unique buckets of commands and then the Foreach-Object block just grabs the first item in each bucket.

BTW if you want all commands saved to a history file I would use the limit value - 32767 - unless that is what you set $MaximumHistoryCount to. :-)

BTW if you want to automatically save this on exit you can do this on 2.0 like so:

Register-EngineEvent PowerShell.Exiting {
    Get-History -Count 32767 | Group CommandLine | 
    Foreach {$_.Group[0]} | Export-CliXml "$home\pshist.xml" } -SupportEvent

Then to restore upon load all you need is:

Import-CliXml "$home\pshist.xml" | Add-History
Keith Hill
hmm ... thanks for the post, but did you leave out the part where assign to $hist?
dreftymac
Sorry, I was just picking a variable name other than $IniFileCmdHistory in order to avoid the dreaded horizontal scrollbar. :-)
Keith Hill
.. oh of course! *slaps forehead* :)
dreftymac
What about just `Get-History | Select -Unique`? That works for me here at least and avoids the grouping and foreach (where I had to look twice before understanding what you do there :-))
Joey
That's what I originally had put as my answer but the resulting object isn't a full fledged HistoryInfo object so when you try to rehydrate the history from file using "Import-Clixml <path> | Add-History" you get an error.
Keith Hill