/* ]]> */
Mar 302010
 

Here’s a handy method to measure elapsed time in powershell. To do this, we will utilize the following two classes:

System.DateTime
System.TimeSpan

Assuming that the variable “$script:StartTime” was set at the beginning of your script, elapsed time can be determined using either of the following methods:

or

Both methods work exactly the same and produce a System.TimeSpan object.

Here’s a sample script to demonstrate the process:

Just another example of how extremely cool Powershell is!

UPDATE

And here’s an easier, more concise, and even better alternative for measuring elapsed time using the “System.Diagnostics.Stopwatch” class:

(Kudos & Thanks to Stephen Mills for this contribution)

Sample Output:

Note that the “Elapsed” property returns values similar to the “TimeSpan” class, so you still have the option of formatting the output if so desired”

 Posted by at 1:00 am

  2 Responses to “Measuring Elapsed Time in Powershell”

  1. The stopwatch object is probably even easier to use.

    $Elapsed = [System.Diagnostics.Stopwatch]::StartNew()
    do { sleep 1 } until ( $Elapsed.ElapsedMilliseconds -ge 3000 )
    Write-Host “Total Elapsed Time: $($Elapsed.Elapsed.ToString())”

    You can also use ToString on timespan objects to return a string in the format of days.hours:minutes:seconds.fractionalSeconds. So if the elapsed time was 1 day, 2 hours, 13 minutes, 22 seconds, and 14 milliseconds, the ToString output would look like:
    1.02:13:22.0140000

  2. Awesome (and way better) alternative – I like it!
    Thank You Stephen – I’ll update the post to show this method as well.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Page optimized by WP Minify WordPress Plugin