.Net StopWatch and Powershell

人走茶凉 提交于 2019-12-13 03:49:17

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/48153565/net-stopwatch-and-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!