Estimating/Calculating Execution Time

Over the years, I’ve noticed that I develop a general routine depending on the needs of my current customer.  When I get to work in the morning I generally check a few items that I know can develop into hot button issues.  As a general rule, if I am going to repeat a task more than a few times, I write a quick script in PowerShell if possible.  Lately I’ve had to search for and modify several tens of thousands of objects in AD.  The majority of my scripts display a progress bar.  The progress bar is nice, but I wanted to improve the progress bar by adding an active countdown timer.

When I set out to write this, I wanted a function I can just drop into a script if I feel it’s necessary, with minimal code changes.  The function I came up with makes the following assumptions:

  • Each processing task takes relatively the same amount of time to execute
  • You must know how many items you are processing.  I’m not sure mathematically how to solve this without knowing both how many items we have looped through and how many more we have left to process
  • If one or several of the processing tasks takes significantly longer than the other processing tasks (such as a network timeout), the estimated time remaining will be skewed

After adding the function I created to a script, all I need to add is this code to my foreach loop (where $cycles is an integer representing the total objects to process):

$i++
ShowExecutionTime -TotalObjectsToProcess $Cycles

Here is the script in action:

CalculateRemainingExecutionTimeRunning

The script in the repository also has a –ShowCalculatedTimes parameter which will document each time the function estimates the script completion time, then will display how many times we guessed each specific completion time.  Below are the results of the script with –ShowCalculatedTimes enabled:

CalculateRemainingExecutionTimeResults

The sample script containing the function can be found here.