r/PowerShell • • Aug 18 '17

Script Sharing How To Create Progress Bars in PowerShell

https://mcpmag.com/articles/2017/08/17/create-progress-bars-in-powershell.aspx
126 Upvotes

12 comments sorted by

View all comments

2

u/jagrock84 Aug 19 '17

Nice article. I only caution that, as with writing to console, it slows down scripts if there are lots of processes. I tend to create a stop watch before the main loop I want to have a progress and only update the progress bar every 1 sec. For script I have running against 50k objects, this can shave off several minutes.

As you can see in the example below, it's 60 seconds updating progress every time. The whole process takes less than a sec in the 2nd one (I put in an extra if condition to force the progress to show at least once).

cls

$sw = New-Object System.Diagnostics.Stopwatch
$sw2 = New-Object System.Diagnostics.Stopwatch

$sw.Start()

$totalTimes = 100000

$i = 0

for ($i=0;$i -lt $totalTimes; $i++) {

    $percentComplete = ($i / $totalTimes) * 100

    Write-Progress -id 1 -Activity 'Doing thing' -Status "Did thing $i  times" -PercentComplete $percentComplete

}

$sw.Elapsed.TotalSeconds

Write-Progress -id 1 -Activity 'Doing thing' -Completed
Start-Sleep -Seconds 1

$sw.Restart()
$sw2.Start()

$i = 0

for ($i=0;$i -lt $totalTimes; $i++) {

    $percentComplete = ($i / $totalTimes) * 100

    If (($sw2.Elapsed.TotalMilliseconds -ge 1000) -or ($i -le 1)) {

        Write-Progress -ID 2 -Activity 'Doing thing2' -Status "Did thing $i  times" -PercentComplete $percentComplete
        $sw2.Restart()

    }

}

$sw.Elapsed.TotalSeconds
Write-Progress ID 2 -Activity 'Doing thing2' -Completed