So you just typed something epic…

… and you want to save it for posterity.

You know what it’s like, you’re prototyping something at the PowerShell command line, and it’s getting a bit complicated. It’s the greatest one-liner in the history of PowerShell, nay! Scripting itself! You’ve been honing this for the last two hours. It’s got fifteen Cmdlets strung together in a giant pipeline, with selecting and sorting and all manner of wizardry. It’s pretty damn awesome.

And you think “Hey, I should be saving this for later re-use or something”

You could copy it out of the host with careful mouse drags, or you could take a screenshot, or you could laboriously re-type it. Except they’re all boooring. And anyway, this one-liner returns such a massive swathe of output that your last command has gone shooting off up the screen somewhere and you can’t find it just by scrolling. And you could always hit the up arrow and everything but who cares? That’s not cool. There has to be a cooler way.

Consider this

Get-History | Select-Object -Last 1 | Out-File History.ps1

Or, better

Get-History | Select-Object -Last 1 -Property CommandLine | Out-File History.ps1

Or, better still

(Get-History | Select-Object -Last 1).CommandLine | Out-File History.ps1

Or, even better than that

(h | select -Last 1).CommandLine | Out-Clipboard

Yes, you can easily access your command history from PowerShell. And just like any other object, you can filter, sort and select or pipe it off to other Cmdlets for consumption. And if you were particularly nerdy and not at all obsessive-compulsive, you could encapsulate this into a cmdlet called “Save-History”, alias that cmdlet to “sh” and put the whole lot into your profile so it’s available onload, and you could save your fiddlings around at the command line for ever and ever and ever. But no-one would be that nerdy, right?

Function Save-History
    (Get-History | Select-Object -Last 10).CommandLine | Out-File $home\History.ps1 -Append

Write-Host "sh -> Save-History is available"
Set-Alias -Name sh -description "sh -> Save-History" -Value Save-History


Leave a Reply

Your email address will not be published. Required fields are marked *