Estimated Completion in Write-Progress in PowerShell
By Anatoly Mironov
Have you also got many sites in your tenant? Write-Progress is the bare minimum in a script that goes through all sites. But there is also another nice way to make easier to see the progress - estimated completion time.
Although the idea comes from another blog post (My life is a message), I thought it could be worth sharing it again, especially in the cloud context.
Here is a bit simplified scenario: Getting information for every site. The status message in Write-Progress contains also the estimated completion time.
# This is just an example for time estimations in write-progress, | |
# though a simplified scenario | |
$sitesBareMinimum = Get-SPOSite -Limit All | |
$starttime = Get-Date | |
$count = 0 # kind of an index, counter | |
$total = $sitesBareMinimum.Count | |
$sites = $sitesBareMinimum | ForEach-Object { | |
$site = $_ | |
$estimation = "" | |
$now = Get-Date | |
if ($count -gt 0) { # noone wants a DividedByZeroException :) | |
$elapsed = $now - $starttime # how much time has been spent | |
$average = $elapsed.TotalSeconds / $count # how many seconds per site | |
$totalSecondsToGo = ($total - $count) * $average # seconds left | |
$span = New-TimeSpan -Seconds $totalSecondsToGo # time left | |
$estimatedCompletion = $now + $span # when it will be complete | |
$estimation = $estimatedCompletion.ToString() # readable estimation | |
} | |
$count++ | |
$percent = 100 * $count / $total # percentage complete | |
$status = "#{0:d5} of $total. Est:d $estimation. $($site.URL)" -f $count # aggregated status message | |
Write-Progress -Activity "Getting information for " -Status $status -PercentComplete $percent | |
$siteWithMoreInfo = Get-SPOSite -Identity $site.URL # the actual time consuming operation | |
$siteWithMoreInfo # return the site with more information | |
} |
I included the comments, and it should be straight forward to follow the logic in the script. Every iteration tries to estimate time, by calculating the average time of time per site, mulplying it by the remainder of the sites and adding it to the current time. The more sites are processed, the more accurate is the estimation.