Estimated Arrival Time (ETA) for PowerShell
Ever had a script that takes a long time to run? Would it be nice to see an estimated time for completion? Well, the code below is for you. ![]()
Percentage complete is an easy calculation for any loop operation. Deriving time from that requires us to hold ($start) with the time our loop began. From there we can multiply out and calculate total seconds. When total seconds remaining is added to the current time .. then … you have ETA. Example below.
# Data Source
$sites = Get-SPSite -Limit All
# Initialize Tracking
$start = Get-Date
$i = 0
$total = $sites.Count
# Loop
foreach ($site in $sites) {
# Progress Tracking
$i++
$prct = [Math]::Round((($i / $total) * 100.0), 2)
$elapsed = (Get-Date) - $start
$totalTime = ($elapsed.TotalSeconds) / ($prct / 100.0)
$remain = $totalTime - $elapsed.TotalSeconds
$eta = (Get-Date).AddSeconds($remain)
# Display
$file = $site.Url.Split('/')[4]
Write-Progress -Activity "Backup $file ETA $eta" -Status "$prct" -PercentComplete $prct
# Operation
Backup-SPSite $site.Url -Path "D:\TEMP\$file.site" -WhatIf
}

Awesome! I had no idea you could actually do something like this. Thanks for Sharing!
Glad you found it helpful. Yeah, in the past I’ve had to calculate in my head and guess. Tell the project manager … should be done between 4PM and 8PM. =)
I believe you need to change .AddSeconds($remain) to be .AddSeconds($remain – $elapsed.TotalSeconds), or with a percentage such at .25:
$dtCurr = Get-Date
$dtElapsed = New-TimeSpan -Start $dtStart -End $dtCurr
$Remain = (($dtElapsed.TotalSeconds) * (1 – $Percent)) / $Percent
$eta = $dtCurr.AddSeconds($Remain)
$TotalEstimatedTime = ($elapsed.TotalSeconds) / ($prct / 100.0)
$remain = $TotalEstimatedTime – $elapsed.TotalSeconds
Thank you Tam! Yes, that is a good catch. PowerShell code update to reflect this.
I like to keep $prct exact, otherwise it becomes less accurate for big loops and can even be zero in the beginning. Maybe round it later for printing:
$prct = $i / $total * 100.0
Yes, Line 13 should have rounding included already.