James O'Neill's Blog

September 12, 2009

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

Filed under: Uncategorized — jamesone111 @ 9:32 pm

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

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 ?

This post originally appeared on my technet blog.


Blog at WordPress.com.

%d bloggers like this: