Calculating how long a PowerShell script takes to run

I put this together to get a handle on some of the longer AD pull / spreadsheet populating scripts that I run. It has some logic in it to return a meaningful display of time (so you don’t get “This script took 0 hours 0 minutes and 7 seconds to run” returned).

First you set a variable at the start of the script to log the exact time it started processing.

#### Start the clock
$s=Get-Date

Then after the bulk of the script (but perhaps before any mails are sent) you can paste the below. It will produce a popup box, so isn’t suitable for script run on a scheduled task.

#### Calculate how long script took to run
$WShell = New-Object -ComObject Wscript.Shell -ErrorAction Stop
$tt = new-timespan -seconds $(($e - $s).TotalSeconds)
IF ( ($tt.TotalSeconds) -lt 60) {
$rt = $tt.seconds
$WShell.Popup("Time taken to run: $rt seconds",0,"Script finished",48+0)
}
ELSEIF  ( ($tt.TotalSeconds) -gt 3599) {
$rt = '{0:00} hours {1:0} minutes {2:00} seconds' -f $tt.Hours,$tt.Minutes,$tt.Seconds 
$WShell.Popup("Time taken to run: $rt",0,"Script finished",48+0)
}
ELSE {
$rt = '{1:0} minutes {2:00} seconds' -f $tt.Hours,$tt.Minutes,$tt.Seconds 
$WShell.Popup("Time taken to run: $rt",0,"Script finished",48+0)
}

The $WShell.Popup entries can be removed and $rt can then be used to add the duration to a text file or e-mail.

Posted in Guides Tagged with:

Leave a Reply

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

*