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.

get-history2