This is a part of an on-going blog series written by Adam Gordon. Each week, Adam will walk you through a PowerShell command, showing you when and how to use each one. This week, Adam covers Write-Progress.
When to use Write-Progress
The Write-Progress cmdlet displays a progress bar in a PowerShell command window that depicts the status of a running command or script.
You can select the indicators that the bar reflects and the text that appears above and below the progress bar.
How to use Write-Progress
Display the progress of nested For loops:
1 2 3 4 5 6 7 8 9 |
for($I = 1; $I -lt 101; $I++ ) { Write-Progress -Activity Updating -Status 'Progress->' -PercentComplete $I -CurrentOperation OuterLoop for($j = 1; $j -lt 101; $j++ ) { Write-Progress -Id 1 -Activity Updating -Status 'Progress' -PercentComplete $j -CurrentOperation InnerLoop } } |
This example displays the progress of two nested For loops, each of which is represented by a progress bar.
The Write-Progress command for the second progress bar includes the Id parameter that distinguishes it from the first progress bar. (Write-Progress -Id 1)
Without the Id parameter, the progress bars would be superimposed on each other instead of being displayed one below the other.
Display the progress while searching for a string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<span style="color: #008000;"># Use Get-EventLog to get the events in the System log and store them in the $Events variable.</span> $Events = Get-EventLog -LogName system <span style="color: #008000;"># Pipe the events to the ForEach-Object cmdlet.</span> $Events | ForEach-Object -Begin { <span style="color: #008000;"># In the Begin block, use Clear-Host to clear the screen.</span> Clear-Host <span style="color: #008000;"># Set the $i counter variable to zero.</span> $i = 0 <span style="color: #008000;"># Set the $out variable to a empty string.</span> $out = "" } -Process { <span style="color: #008000;"># In the Process script block search the message property of each incoming object for "install".</span> if($_.message -like "*install*") { <span style="color: #008000;"># Append the matching message to the out variable.</span> $out=$out + $_.Message } <span style="color: #008000;"># Increment the $i counter variable which is used to create the progress bar.</span> $i = $i+1 <span style="color: #008000;"># Use Write-Progress to output a progress bar.</span> <span style="color: #008000;"># The Activity and Status parameters create the first and second lines of the progress bar heading, respectively.</span> Write-Progress -Activity "Searching Events" -Status "Progress:" -PercentComplete ($i/$Events.count*100) } -End { <span style="color: #008000;"># Display the matching messages using the out variable.</span> $out } |
Need PowerShell training? Check out ITProTV’s PowerShell online IT training courses.