Skip to content

34. Using the progress bar

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

A progress bar can be used to show something is in a process. It is a time-saving and slick feature one should have.

Progress bars are incredibly useful while debugging to figure out which part of the script is executing, and they’re satisfying for the people running scripts to track what’s happening. It is common to display some kind of progress when a script takes a long time to complete. When a user launches the script and nothing happens, one begins to wonder if the script launched correctly.

34.1: Simple use of progress bar

1
2
3
4
5
1 .. 100 | ForEach-Object -Process {
  Write-Progress -Activity 'Copying files' -Status "$_ %" -Id 1 -PercentComplete $_ -CurrentOperation "Copying file file_name_$_.txt"
  Start-Sleep -Milliseconds 500
  # sleep simulates working code, replace this line with your executive code (i.e. file copying)
}

Please note that for brevity this example does not contain any executive code (simulated with Start-Sleep ). However it is possible to run it directly as is and then modify and play with it._

34.2: Usage of inner progress bar

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
1 .. 10 | ForEach-Object -Process {
  $fileName = "file_name_$_.txt"
  Write-Progress -Activity 'Copying files' -Status "$($_*10) %" -Id 1 -PercentComplete ($_* 10 ) -CurrentOperation "Copying file $fileName"

  1 .. 100 | ForEach-Object -Process {
    Write-Progress -Activity "Copying contents of the file $fileName" -Status "$_ %" -Id 2 -ParentId 1 -PercentComplete $_ -CurrentOperation "Copying $_. line"
    Start-Sleep -Milliseconds 20 # sleep simulates working code, replace this line with your executive code (i.e. file copying)
    Start-Sleep -Milliseconds 500 # sleep simulates working code, replace this line with your executive code (i.e. file search)
  }
}