Remember PowerShell Command History Between Sessions
October 30th, 2011
I noticed Eric Williams asking people on Twitter to vote for a Microsoft Connect issue logged against PowerShell. The feature that Eric is looking for is the ability to have access to the command history from your previous session(s).
The Microsoft Connect entry has a link to a workaround but that workaround looks like it is targeting PowerShell V1 as it proposes that you add a “bye” function to your profile which will save your history. This will work, but PowerShell V2 added support for event subscription/handling. This seems like a much better place to extend PowerShell to support the functionality Eric is looking for.
Maybe I’m missing something, but I gave this a shot and it seems to work. I’m not sure this is exactly what he’s looking for but I’ll post it in case it moves us in the right direction. Put the following script in your profile somewhere. I put this in my $profile.CurrentUserAllHosts file.
$profileFolder = Split-Path -Path ($profile.CurrentUserAllHosts) -Parent
$historyFile = Join-Path -Path $profileFolder -ChildPath history.csv
$exportHistoryAction = {
Get-History | Export-Csv -Path $historyFile
}
if (Test-Path -Path $historyFile) {
Import-Csv -Path $historyFile | Add-History
}
Register-EngineEvent -SourceIdentifier ([System.Management.Automation.PsEngineEvent]::Exiting) -Action $exportHistoryAction | Out-Null
Give it a try and let me know what you think.
References:
Cheers, Dan


Sorry, comments are closed for this article.