Progress bar Example




When working with large loops that take a lot of time it’s nice to know that something happens and the script is making progress. You can use write-host $item to write something that is  unique in the loop or even better use the count method on the variable that you have stored the data you want to loop and then use an integral to count up. if you do that you can easily use the write-progress cmdlet to get a nice progress bar.

I often end up working with foreach  loops and here is an example how to use the write-progress in an foreach loop. In this example I use the status-parameter to get the xxx services out of 235 is done counter and the PercentComplete-paratmeter. I use an integral that I set to 0 in the beginning and then ad 1 in each foreach loop,in that way I can easily track how many of the 235 items that I have looped through. To get the percentage I need to divide the int every time with the total I got from the count method, in this case 235 and then multiply it with 100 to get the percent.


$service = Get-Service
$i = 0
$int = $service.Count 

foreach ($item in $service)
    Write-Host $item
    Write-Progress -Activity "List all services" -PercentComplete ($i / $service.Count*100) -Status "$i services out of $int is done"