Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net StopWatch and Powershell

I have a powershell script that is currently running every 4 hours via task scheduler. It cleans a drive and when it's done it fires off an email to me telling me what it moved and where and the amount of time it took to perform this task.

However, I seem to be having issues with the time it displays at the end. I recently got an email that it took 4 minutes, when I know that it took closer to 30 minutes.

The basic structure looks like this:

$StopWatch = new-object system.diagnostics.stopwatch
$StopWatch.Start()

Do { All this stuff }       
While(This condition is false)

$StopWatch.Stop()
$Minutes = $StopWatch.elapsed.minutes

What am I missing here? This thing is just reading the system time and then comparing it to the current time whenever .elapsed is accessed right?

like image 225
Ochuse Avatar asked Dec 13 '22 18:12

Ochuse


1 Answers

Try using $StopWatch.Elapsed.TotalMinutes instead of $StopWatch.Elapsed.Minutes

The latter will not count beyond 59 so for a task that took 64 minutes to run, the Minutes property will only show 4. The Hours property in this particular example however would have increased to 1, up from 0.

You could easily verify/try this out using the same object you already have but by looking at the Seconds/TotalSeconds properties instead since it follows the same logic.

$StopWatch = new-object system.diagnostics.stopwatch
$StopWatch.Start()

Do { All this stuff }       
While(This condition is false)

$StopWatch.Stop()
$Minutes = $StopWatch.Elapsed.TotalMinutes
like image 98
notjustme Avatar answered Feb 02 '23 06:02

notjustme