Write-Progress powershell command

Write-Progress | Taking on PowerShell one cmdlet at a time | Weekly Blog

Share this post:

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:

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.

Write-Progress powershell command

 

Display the progress while searching for a string:

# Use Get-EventLog to get the events in the System log and store them in the $Events variable.
$Events = Get-EventLog -LogName system
# Pipe the events to the ForEach-Object cmdlet.
$Events | ForEach-Object -Begin {
    # In the Begin block, use Clear-Host to clear the screen.
    Clear-Host
    # Set the $i counter variable to zero.
    $i = 0
    # Set the $out variable to a empty string.
    $out = ""
} -Process {
    # In the Process script block search the message property of each incoming object for "install".
    if($_.message -like "*install*")
{
        # Append the matching message to the out variable.
        $out=$out + $_.Message
    }
    # Increment the $i counter variable which is used to create the progress bar.
    $i = $i+1
    # Use Write-Progress to output a progress bar.
    # The Activity and Status parameters create the first and second lines of the progress bar heading, respectively.
    Write-Progress -Activity "Searching Events" -Status "Progress:" -PercentComplete ($i/$Events.count*100)
} -End {
    # Display the matching messages using the out variable.
    $out
} 

Write-Progress powershell command

Write-Progress powershell command

Write-Progress powershell command

Need PowerShell training? Check out ITProTV’s PowerShell online IT training courses.

Leave a Reply

Your email address will not be published. Required fields are marked *