r/PowerShell • u/icebreaker374 • Sep 17 '26
Question Write-Progress
Looking for opinions...
When using Write-Progress inside of for/Foreach loops and using a counter stored in a variable defined outside the loop, do you start the counter at 0 or 1, and why?
13
Upvotes
View all comments
Show parent comment
5
u/HeyDude378 Sep 17 '26
I say that's not clean code because it will report some progress before any work is done. Obviously for quick and dirty code it's fine, but if I want clean code, I'm doing this:
(Supposing 100 objects) On the first iteration of the loop, it will say that it's checking Computer 1 and write that progress is 0. On the second iteration of the loop, it will say that it's checking Computer 2 and that Progress is 1%. That seems right to me... if we're still checking the second computer, we're not at 2% complete yet. On the 100th computer, it will say that it's at 99%, then it will check the last computer, then it will complete.
With $i++ at the beginning, we don't know how long "do work here" takes, but what if it took 10 minutes? That would give us two problems: during the first loop, less than a second in we will see "1% complete", and we might think means that the whole script will run extremely quickly, since we got to 1% progress in milliseconds. So we've had some bad information communicated to us at the beginning. Then also at the end, we'll be on "100% complete" for 10 minutes. If the script was 100% complete we wouldn't still be running for 10 minutes, so that's false information there too.
So that's my thinking. If you're the only user of your own script and you know what to expect, none of this really matters. But I personally hate seeing 100% on a progress bar. If it was done I wouldn't still be seeing the bar.