How to write a one-liner progress bar

How to write a one-liner progress bar

Powershell has an easy to use and built-in cmdlet named Write-Progres.

However, displaying the PercentComplete parameter seems sometimes cumbersome.

Fortunately, most of the time, you need a progress bar when you are inside a foreach loop. This makes it easy to handle because the object you enumerate has a Count and an IndexOf properties.

Basic progress bar

For example, let’s assume you want to enumerate shares.

foreach($Share in $ShareList)
{
Write-Progress -Id 1 -Activity 'Enumerating shares' -PercentComplete ($ShareList.IndexOf($Share)/$ShareList.Count*100)
#Doing some stuff
}

Nested progress bar

The only difference here is that you add the ParentId parameter.
In case you forget or omit this parameter, the second progress bar is displayed under the first one without indentation.

In the next example, let’s assume you want to enumerate files from the shares of the first progress bar.

foreach($File in $FileList)
{
Write-Progress -Id 2 -ParentId 1 -Activity 'Enumerating files' -PercentComplete ($FileList.IndexOf($File)/$FileList.Count*100)

#Doing some stuff
}

Adding a status with the number of items

If we use the former example again and add a status to display the item number reported to the total, this could give:

foreach($File in $FileList)
{
Write-Progress -Id 2 -ParentId 1 -Activity 'Enumerating files' -PercentComplete ($FileList.IndexOf($File)/$FileList.Count*100) -Status "$($FileList.indexof($file)) of $($FileList.count)"

#Doing some stuff
}

Going faster

If you feel comfortable with them, you can use an accelerator.
However, the gain is relatively small.

foreach($Share in $ShareList)
{
Write-Progress -Id 1 -Activity 'Enumerating shares' -PercentComplete ([array]::IndexOf($ShareList,$Share)/$ShareList.Count*100)
#Doing some stuff
}

On the contrary, don’t forget that the Write-Progress cmdlet itself consumes processor time. Depending on the frequency you call it, it can notably slow down your scripts.

More about

Write-Progress (MSDN)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s