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

8

u/Thirdbeat Aug 18 '17

Great article! I wish I had this when I started powershell Just a comment: you should add that one can set write-progress -complete after processing is done and that the activity sets the "unique Id" so you can have several write progresses. Also mabye show how it's done when processing an array (using for instead of foreach) Just my 2 cents

2

u/gigglestick Aug 19 '17

One should use the -Id parameter for multiple progress bars. Activity is not a unique Id. For evidence, try the two following examples:

# This one will show a single progress bar, switching between A and B values:
for ($a = 10; $a -le 100; $a += 10) { 
    for ($b = 10; $b -le 100; $b += 10) { 
        Write-Progress -Activity "A = $a"
        Start-Sleep -Milliseconds 100
        Write-Progress -Activity "B = $b"
        Start-Sleep -Milliseconds 100
    }
}

# This one will show two separate progress bars, one showing A values and one showing B values:
for ($a = 10; $a -le 100; $a += 10) { 
    for ($b = 10; $b -le 100; $b += 10) { 
        Write-Progress -Id 0 -Activity "A = $a"
        Start-Sleep -Milliseconds 100
        Write-Progress -Id 1 -Activity "B = $b"
        Start-Sleep -Milliseconds 100
    }
}

2

u/Thirdbeat Aug 19 '17

You know what, you are absolutely right. I was certain i had written some code that did multiple progress-bars this way, but upon testing i found out i was wrong. I'm sorry.

But i do have to add that while it is supported that only one have -ID, you cannot choose 0 ;)

2

u/gigglestick Aug 19 '17 edited Aug 20 '17

In fact, zero is the default ID, and can be specified. My code above works, as does the following without -Id on the first one because the default of the first one is zero.

Edit: Microsoft's documentation says there's no default ID, but if you change "-Id 1" to "-Id 0" in the following code, they both end up overwriting the same progress bar, which implies to me that the one without an ID is using 0 by default.

for ($a = 10; $a -le 100; $a += 10) { 
    for ($b = 10; $b -le 100; $b += 10) { 
        Write-Progress -Activity "A = $a"
        Start-Sleep -Milliseconds 100
        Write-Progress -Id 1 -Activity "B = $b"
        Start-Sleep -Milliseconds 100
    }
}

it is supported that only one have -ID

This works with 12 progress bars, addressing them by unique ID:

for ($loop = 10; $loop -le 100; $loop += 10) { 
    for ($id = 0; $id -le 12; $id++) { 
        Write-Progress -Id $id -Activity "$id - $loop"
        Start-Sleep -Milliseconds 10
    }
    Start-Sleep -Seconds 1
}