Have you ever ran a command or script and wanted to know how long it takes to complete but forgot to wrap the code or script with Measure-Command? Well, you are in luck because you can take a look at the history using Get-History and check out the StartExecutionTime and EndExecutionTime to determine how long it took the command to run!
Lets run a simple command such as Get-ChildItem on my C:\Windows\System32 directory.
Get-ChildItem C:\Windows\System32
Ok, now that we have done that, we need to use Get-History to get the time it took to complete the command by subtracting StartExecutionTime from EndExecutionTime to get that answer.
(Get-History)[-1].EndExecutionTime - (Get-History)[-1].StartExecutionTime
As you can see, the command took just over 9 seconds to run. Now this isn’t a replacement for Measure-Command, but it does provide a decent way to find out how long a command took to run. The [-1] that I used means that I am getting the last member of the collection.
Pretty cool stuff, but I wanted an easier way to get this information without having to type out that command. So naturally, I made this into a simple function that you can use below.
Code
With this function, you can simply run it after a command to find out how long the last command took to run.
Function Get-LastCommandExecutionTime { <# .SYNOPSIS Gets the execution time of the last command used. .EXAMPLE Get-LastCommandExecutionTime Description ----------- Gets the last execution time of the last command run. #> Process { (Get-History)[-1].EndExecutionTime - (Get-History)[-1].StartExecutionTime } }
Get-Command Get-LastCommandExecutionTime
Nothing revolutionary, but still something that you might find useful in your scripting journeys.
Enjoy!
Pingback: Episode 192 – Eric Williams from Cisco on the UCS PowerTool « PowerScripting Podcast