Home > front end >  How to use Powershell write-progress parameter with unknown seconds remaining to complete
How to use Powershell write-progress parameter with unknown seconds remaining to complete

Time:10-07

Trying to show approximate unknown time to finish the Write-process in PowerShell 'for' loop. Write-process have a parameter '-SecondsRemaining' to show remaining time below progress bar with text 'remaining'. Bit not able to show remaining time to finish the loop.

Failed attempts

($i-$_) increments the time with each iteration with 'remaining' text, shows time elapsed

(-1-$_) not working

(10-$_) hardcoded 10 seconds

Code sample

for ($i=1;$i -le 10000;$i  )
{
Write-Host "Iteration $i"
Write-Progress -Activity "Write-progress with seconds remaining" -Status "$i Completed" -SecondsRemaining ($i-$_)
}

Some References

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-progress?view=powershell-7.2

https://morgantechspace.com/2018/05/powershell-show-progress-bar-status-and-percent-completed.html#:~:text=PowerShell : Show Progress Bar, Status and %,completed for a long running command or script.

CodePudding user response:

You can get a rough estimate by extrapolating from the elapsed time and how many items you've processed to that point:

$maxItems = 10000
$startTime = Get-Date

for ($i = 1; $i -le $maxItems; $i  )
{
    # Do some work
    Write-Host "Iteration $i"

    # Calculate the timings
    $elapsed = ((Get-Date) - $startTime).TotalSeconds
    $remainingItems = $maxItems - $i
    $averageItemTime = $elapsed / $i

    # Update the user
    Write-Progress -Activity "Write-progress with seconds remaining" -Status "$i Completed" -SecondsRemaining ($remainingItems * $averageItemTime)
}
  • Related