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.   shades_smile

 

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.

 

image

 

# 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
}

7 Comments

    1. 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. =)

  1. 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)

  2. 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

Leave a Comment

Return to Top ▲Return to Top ▲