PowerShell Cmdlet Quickie: New-TimeSpan

As is the case with most things, when I find a way for getting something done in a script that is “good enough”, I’ll tend to stick with that method until that method no longer becomes fit for purpose. One such method is printing out the time that something took in PowerShell: many of the scripts on my site use this method to get the duration of a task, and I’ve been using this since PowerShell 1.0:

$date1=get-date

#do something
 
$date2=get-date
$taskTime = "Task took "  ($date2-$date1).Hours " Hours, " ($date2-$date1).Minutes " Mins, " ($date2-$date1).Seconds " Secs "
write-output $taskTime

This was always great for informational purposes, it always felt ugly, and I needed to include day,month etc to the interval, so the command was going to get even longer and even uglier. I needed an alternative.

So I was pleased to discover that, way back in 2012 when PowerShell 3.0 was released, the cmdlet “Get-TimeSpan” was released. You can use this to represent a time interval between two dates (the hint is in the name!)
So now, time-span between two dates can be measured like so:

$date1=get-date

#do something
 
$date2=get-date
$taskTime = "Task took(HH:MM:SS:MS) "+(New-TimeSpan –Start $date1 –End $date2)
write-output $taskTime
 

This is so much easier, and a lot neater.

Author: Richie Lee

Full time computer guy, part time runner. Full time Dad, part time blogger. Pokémon Nut. Writer of fractured sentences. Maker of the best damn macaroni cheese you've ever tasted.

1 thought on “PowerShell Cmdlet Quickie: New-TimeSpan”

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s