James O'Neill's blog

Windows Platform, Virtualization and PowerShell with a little Photography for good measure.

How to use $myInvocation to do simple command profiling in PowerShell

How to use $myInvocation to do simple command profiling in PowerShell

  • Comments 2
  • Likes

One of the things I’ve noticed on our internal PowerShell DL is that some of the Redmond cognoscenti like to have the history ID in their PowerShell prompt and I was never sure how they did it. 
Then the other day I noticed it was part of the $MyInvocation automatic variable, so it is easy enough to add that to the prompt function - in case you didn't know PowerShell calculates the prompt with a function, so all kinds of creativity can be deployed there.

Over the last day or so I have been playing with some stuff in PowerShell which takes a long time to run. My old university tutor would be glad that I worked out the algorithm I’m using will take Order n-cubed time to run. I can’t see an improvement to the overall way of solving the problem, but I can put some short cuts in. What I wanted to know was whether it would run any quicker. One neglected part of the History in PowerShell is that that gives you start and end execution time, so I ended up doing this

h    #Alias for get-History

note the last number for example 123,

$hh=h 123
$hh.EndExecutionTime.Subtract($hh.StartExecutionTime)

Putting the history item in a variable lets me use [tab[ to expand the EndExecutionTime , Subtract and StartExecutionTime so it actually saves typing

Thinking about $MyInvocation.History, I realized I could automate this, and just added the following to my profile

function howLongWasthat {
  (get-history ($MyInvocation.HistoryId -1)).endexecutiontime.subtract((get-history ($MyInvocation.HistoryId -1)).startexecutiontime).totalseconds
}

 

So now after running a command I type how [tab] [enter] and hey presto it gives me the run time. 

Following on from my previous post , do you have any magic profile entries to share ?



Comments
  • I took a similar approach to display the last command execution time in PowerShell's window title: http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2008/03/10/custom-powershell-prompt.aspx

  • $MyInvocation.HistoryId do not exist in Powershell version 1.

    Function howLongWasthat {

      #Powershell v1

     $Lastcmd=Get-History -count 1

     $Lastcmd.endexecutiontime.subtract($Lastcmd.startexecutiontime).totalseconds

    }

    Thanks you.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment