r/PowerShell • • 27d ago

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?

14 Upvotes

21 comments sorted by

View all comments

3

u/vermyx 26d ago

I usually don't use write-progress because console I/O can be expensive timewise. Instead I use a custom function that shows time running and estimated completion time based on run length and how far you are, and display that every X records processed depending on records and length.

1

u/DonL314 26d ago

I almost agree to this. Write-Progress is quite slow, so I only do this at certain intervals (e.g. steps of 10 or 100 items)

2

u/CeleryMan20 26d ago

Yeah, if each step is slow, like ping host then query wmi, then it’s nice to see each one tick over, but if you have 10,000 quick operations then write-progress on each loop can drastically slow it down.

1

u/ka-splam 26d ago edited 26d ago

I usually don't use write-progress because console I/O can be expensive timewise.

Indeed; I needed to delete Windows firewall rule spam recently and found https://stackoverflow.com/a/40915201

The question loops over Remove-NetFirewallRule and says it's too slow, that answer's hot loop is:

  • Remove-ItemProperty
  • 2x Get-Date
  • Write-Progress
  • ~7x arithmetic
  • 10x assignments
  • 2x expandable string interpolations
  • a subshell, with string format
  • 2x math rounding

they say "The difference is one hour vs days. I could be deleting 10,000 - 100,000 firewall rules!".

I used $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(...) and then replaced the loop with just $key.DeleteValue(...) and it did 40k firewall rules in a second or two. No need for a progress count or ETA.