Timewatch, a PowerShell Function for reporting how much time is left in a loop

I had to loop through a bunch of things the other day and wanted to have a nice way to report how far I was through the loop.

This way if I had 1000 things to loop through, and each one took 10 seconds, I knew I had 10,000 seconds to wait, or roughly 2.7 hours.

Armed with this information, I could be comfortable stepping away for a bit with a good guess as to when my script would finish.

function timewatch
{
    param(
	 [int]$totalnumber,
	 [int]$passnumber
   )	
   $now  = get-date 
   $timespan = $now - $script:starttime
   write-host "It's taken $timespan to complete $passnumber iterations ($($totalnumber - $passnumber) iterations remaining)" -foregroundcolor magenta
   
   $timeper = $timespan.TotalSeconds / $passnumber 
   write-host "Thats $($timeper.tostring("#.#")) seconds per change" -foregroundcolor magenta
   
   $remainingSeconds = ($totalnumber - $passnumber ) * $timeper
   $remainingspan = new-timespan -seconds $remainingseconds 
   write-host "Estimated $($remainingspan.hours.tostring("00")):$($remainingspan.minutes.tostring("00")):$($remainingspan.seconds.tostring("00")) (H:M:S) until complete" -foregroundcolor magenta
 
   $eta = $now.addseconds($remainingSeconds)
   write-host "The current eta for script completion is $eta" -foregroundcolor magenta
}

To use the function above, you need to paste it into your script, somewhere above where you intend to call it.

Then in your script you likely have a loop like this:

foreach($thing in $lotsofthings)
{
  #Do something here with one $thing at a time.
}

To make use of the timewatch function, we’ll modify our loop as follows:

$script:starttime = get-date 
$i = 0
foreach($thing in $lotsofthings)
{
    $i++
    #Do something here with one $thing at a time.
    timewatch -passnumber $i -totalnumber $lotsofthings.count
}

That’s it, now the timewatch function will track the average time per iteration, and based on how many remaining interations are left, will report both the amount of time left, and an ETA time that the looping would complete.

Leave a Reply