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.