Copy Get-History to Clipboard


I’ve been working on a little project, and the need to retrieve the last n number of commands I’ve executed in PowerShell has become a tedious task.  As you’re (hopefully) aware, Get-History is a great cmdlet to review exactly how you got to where you are.  You can then combine that with the Clip cmdlet to copy it to your clipboard for use elsewhere (such as documentation or an email).

For example:

PS C:\> Get-History
 Id CommandLine 
 -- ----------- 
 1 . $PROFILE 
 2 cls 
 3 cd \ 
 4 cls 
 5 Write-Host foo 
 6 Write-host bar 
 7 Write-Host foo bar 
 8 cls 
 9 Get-Date 
 10 Get-Date -Format yyyy-MM-dd 
 11 $Date = Get-Date -Format yyyy-MM-dd 
 12 $Date = Get-Date -Format YY-MM-dd 
 13 $date 
 14 $Date = Get-Date -Format yy-mm-DD 
 15 $Date 
 16 $Date = Get-Date -Format yy-MM-dd 
 17 $Date 
 18 cls 
 19 get-history

So, if I wanted to store the command on line 11 in the clipboard, I could run:

(Get-History 10).CommandLine | Clip

Obviously, as you add more things to your PowerShell history, the number increases, and I’m always look at a Get-History output to grab what the last 3 or 4 commands were that I ran in sequence, which requires Get-History, and then looking at the last n lines and grabbing them.  To make my life easier, I created a function to grab the last n commands:

# Get Last Command
Function GetLastCommand($Number)
    $CommandLength = (Get-History | Measure-Object).Count
    $Start = $CommandLength - $Number + 1
    [array]$CommandRange = @()
    Foreach ($obj in ($Start..$CommandLength)) { $CommandRange+=$obj; $obj++ }
    (Get-History $CommandRange).CommandLine | Clip
    Write-Host -NoNewline "Last ";Write-Host -NoNewLine -ForegroundColor Green "$($Number) ";Write-Host "commands have been copied to the clipboard."

Simply drop it in $PROFILE, and then run GetLastCommand [int] to copy the last [int] of commands to your clipboard.





Published by Aaron Guilmette

Helping companies conquer inferior technology since 1997. I spend my time developing and implementing technology solutions so people can spend less time with technology. Specialties: Active Directory and Exchange consulting and deployment, Virtualization, Disaster Recovery, Office 365, datacenter migration/consolidation, cheese.

Reader Comments

  1. Hi Aaron,

    Thanks for the function!

    Isn’t your script a very complicated way of doing:

    Get-History | Select -Last 2 | Clip


    (Get-History).CommandLine | select -Last 5 | Clip

    These should give you the same result, right?

    1. You could do those, too. 🙂 However, if you don’t first change $FormatEnumerationLimit to -1, your Get-History result will be truncated. If you put it into a variable, all of the cmdlet is captured.

      Also, sometimes, I like making Rube Goldberg contraptions. 😉

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.