Copy-History – Copy a Previous Command to the Clipboard

It’s great that I can see my history with Get-History, but what if I want to edit it?  I can hit up-arrow to find it, but that doesn’t work if I copy-and-paste functions into my PowerShell window as I write/test the function?  In that case, I have to hit up-arrow through each line that I pasted.  Not fun. 

Also, if you’re like me, your one-liners sometimes include foreach-loops  and if-branches on top of an oil refinery’s worth of pipelines.  These easily exceed the PowerShell window width, so copying that command will include a bunch of unwanted linefeeds.

Here’s a way to stuff the command into my clipboard.  Alt+Space, E, P will paste it into the window, but it’s also handy to paste into IM windows or emails.  

 function Copy-History
{
    param ( [int]$Id = (Get-History -Count 1).Id );

    $history = Get-History -Id $Id -ErrorAction SilentlyContinue -ErrorVariable getHistoryError;

    if ($getHistoryError)
    {
        Write-Warning "$($MyInvocation.MyCommand.Name): $($getHistoryError.Exception.Message)";
    
    } # if ($getHistoryError) ...
    else
    {
        $history.CommandLine | clip.exe;
    
    } # if ($getHistoryError) ... else

} # Copy-History

New-Alias -Force -ErrorAction SilentlyContinue chy Copy-History;