Progress Bar Tricks (Part 2)

by May 13, 2023

Publishing on – Mon May 15

The built-in PowerShell progress bar supports a “real” progress indicator provided you submit a “percentCompleted” value in the range of 0 to 100:

0..100 | ForEach-Object {
    $message = '{0:p0} done' -f ($_/100)
    Write-Progress -Activity 'I am busy' -Status $message -PercentComplete $_

    Start-Sleep -Milliseconds 100
}

To show a “real” progress indicator, your script therefore needs to “know” how much of a given task has been processed yet.

Here is a modified example that defines how many tasks need to be processed, then calculates the percent completed from this:

$data = Get-Service  # for illustration, let's assume you want to process all services

$counter = 0
$maximum = $data.Count  # number of items to be processed

$data | ForEach-Object {
    # increment counter
    $counter++
    $percentCompleted = $counter * 100 / $maximum
    $message = '{0:p1} done, processing {1}' -f ($percentCompleted/100), $_.DisplayName
    Write-Progress -Activity 'I am busy' -Status $message -PercentComplete $percentCompleted

    Write-Host $message
    Start-Sleep -Milliseconds 100
}

Tweet this Tip! Tweet this Tip!