Tome's Land of IT

IT Notes from the Powertoe – Tome Tanasovski

Powerbits 10.5 History Revisited hg & he

Not too long ago, I posted a powerbit for a function that I was using called hgrep.  This is the evolution of that function and how I use it ALL the time in Windows PowerShell.

Here are the two functions, hg (history grep) and he (history execute).  Note: hg is also used by mercurial so feel free to change the alias to suit your needs – you can get the gist with a license to use/modify it off of github.

function Get-HistoryGrep {
    param(
        [Parameter(Mandatory=$false, Position=0)]
        [string]$Regex
    )
    get-history |?{$_.commandline -match $regex}
}

function Invoke-History {
    param(
        [Parameter(Mandatory=$true, Position=0)]
        [int]$Id
    )
    get-history $Id |%{& ([scriptblock]::create($_.commandline))}
}

new-alias hg Get-HistoryGrep
new-alias he Invoke-History

Basically, the functions are used like this:

“Oh man, I need to re-execute that function again – it was an invoke-pester command, but it had a bunch of switches that I got wrong, and then finally got right”

PS C:\test> hg pester

  Id CommandLine
  -- -----------
   5 Invoke-Pester -TestName 'test1' -OutputXml out.xml
   6 Invoke-Pester -TestName 'test1' -OutputFile out.xml
   7 Invoke-Pester -TestName 'test1' -OutputFile out.xml -OutputFormat nunitxml

“Oh, that’s the one, number 7! Let me run that again”

PS C:\test> he 7

Now, you can reuse the above over and over without having to look it up. This is exactly how you code in Linux in the shell. The equivalent in Linux is this:

history |grep pester
!7

Unfortunately, we can’t use the “!” special character in PowerShell because it is reserved to inverse boolean values. However, the general workflow is the same.  If you develop, live, and probably one day die in the shell, then these two functions are essential to your daily life.

One final note, if you run over 4096 commands in the shell, by default “he” won’t work with the earliest commands.  You can modify the special variable, $MaximumHistoryCount, if you want to change this behavior

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: