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)"