Time Your Script with Timespan Objects

Time Your Script with Timespan Objects

Speed and consistency are the two main reasons people automate tasks using PowerShell. Give your script the same inputs and it should produce the same outputs. The consistency concept is easy. What about how much time is saved using PowerShell? We can achieve this using the Timespan object built into PowerShell.

Start and Stop Times

A rudimentary way of keeping track of time in your code is to use Get-Date.

$StartTime = Get-Date

Divide-Number -Dividend 39 -Divisor 3

$EndTime = Get-Date

Saving the start time and end times using Get-Date allows you to later subtract the two times to get an object whose type is Timespan. Timespans are simply the time between two datetime objects. Want to know how many days until Christmas 2020?

$Christmas = Get-Date 12/25/2020
$Now = Get-Date
$Christmas.Subtract($Now) | Select-Object -ExpandProperty Days


Another way to time your scripts is to use the Measure-Command cmdlet. Measure-Command takes in an expression or script block and spits out how long it took to ran.

 Measure-command { Get-Module -ListAvailable }

This will give you the timespan between the start of the command and the end.

Formatting Timespan

Simply knowing how long a script took is nice, but how about formatting the output for a report.

Measure-Command { 
    Start-Sleep -Seconds (Get-random -Minimum 2 -Maximum 29) 

$Timespan = Measure-Command { 
    Start-Sleep -Seconds (Get-random -Minimum 2 -Maximum 29) 

This should produce output similar to “The command finished in 0:00:10.0013427”.

Now that you know how to generate timespan objects add the following code to your profile.ps1 file to countdown until New Years.

$CurrentYear = Get-date | Select-Object -ExpandProperty Year
$NewYears = Get-Date "1/1/$($CurrentYear + 1) 00:00:00"
$Timespan = $NewYears.Subtract($(Get-date))
"Days Until New Years $($Timespan.Days)"

3 thoughts on “Time Your Script with Timespan Objects

  1. FYI, if you use the HistoryPx module (in the PowerShell Gallery), every command you run is measured and you can see the results in the command history. This is helpful because you can try various versions of a command one after another without worrying about using Measure-Command or adding code to time it, and history will capture and output the time for you.

  2. Two steps:
    1. Manually import HistoryPx with Import-Module (it won’t autoload because it proxies built-in cmdlets that will be discovered by default).
    2. Invoke Get-History (or h) to see the history, which includes how long commands took to run, whether or not there were errors, how many items were output, if a terminating error was encountered, plus a few more goodies in an update I’m testing right now.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.