Progress Bar Tricks (Part 1)

by May 11, 2023

PowerShell comes with a built-in progress bar. It typically automatically disappears when your script is done:

Write-Progress -Activity 'I am busy' -Status 'Step A'
Start-Sleep -Seconds 2
Write-Progress -Activity 'I am busy' -Status 'Step B'
Start-Sleep -Seconds 2

If you want to close the progress bar while your script is still running, you need to use the -Completed switch parameter:

Write-Progress -Activity 'I am busy' -Status 'Step A'
Start-Sleep -Seconds 2
Write-Progress -Activity 'I am busy' -Status 'Step B'
Start-Sleep -Seconds 2
Write-Progress -Completed -Activity 'I am busy'
Write-Host 'Progress bar closed, script still running.'
Start-Sleep -Seconds 2

As you can see, closing a progress bar requires to also specify the -Activity parameter because it is a mandatory parameter. However, if you just want to close all visible progress bars, the value of -Activity parameter does not matter. You could as well submit a “space” or a number. Any value will do (except for null values or empty strings as they will not be accepted by mandatory parameters):

Write-Progress -Activity 'I am busy' -Status 'Step A'
Start-Sleep -Seconds 2
Write-Progress -Activity 'I am busy' -Status 'Step B'
Start-Sleep -Seconds 2
Write-Progress -Completed -Activity ' '
Write-Host 'Progress bar closed, script still running.'
Start-Sleep -Seconds 2

Alternatively, you could define a default value for the -Activity parameter:

$PSDefaultParameterValues['Write-Progress:Activity']='xyz'  

Now, Write-Progress would accept the -Completed parameter without having to submit -Activity parameter:

Write-Progress -Activity 'I am busy' -Status 'Step A'
Start-Sleep -Seconds 2
Write-Progress -Activity 'I am busy' -Status 'Step B'
Start-Sleep -Seconds 2
Write-Progress -Completed # due to the previously defined new default value, -Activity can now be omitted
Write-Host 'Progress bar closed, script still running.'
Start-Sleep -Seconds 2


Tweet this Tip! Tweet this Tip!