Quick-Hits: How Long Did That Last Command Take?

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

image

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

image

Nothing revolutionary, but still something that you might find useful in your scripting journeys.

Enjoy!

About these ads

About Boe Prox

Sr. Systems Administrator who uses Powershell daily for everything from reporting to automating daily tasks to just seeing what I can do with it.
This entry was posted in powershell and tagged , , . Bookmark the permalink.

One Response to Quick-Hits: How Long Did That Last Command Take?

  1. Pingback: Episode 192 – Eric Williams from Cisco on the UCS PowerTool « PowerScripting Podcast

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 )

Connecting to %s