Write Progress - PowerShell


Overview

Write-Progress updates the progress of a long-running operation in the PowerShell console. It provides visual feedback to users, indicating the progress percentage and estimated time remaining. This command is often used in scripts and functions to keep users informed during lengthy processes.

Syntax

Write-Progress [-Activity] <string> [-Status] <string> [-PercentComplete] <int> [-SecondsRemaining] <int> [-Id] <object> [-SourceArgs] <object>

Options/Flags

  • -Activity: Specifies a brief description of the current activity.
  • -Status: Provides additional details about the progress or any potential issues.
  • -PercentComplete: Sets the percentage of completion (0-100).
  • -SecondsRemaining: Displays the estimated time remaining in seconds.
  • -Id: Assigns a unique identifier to the progress bar.
  • -SourceArgs: Passes additional arguments to the progress bar source.

Examples

Simple Progress Bar:

$total = 100
for ($i = 1; $i -le $total; $i++) {
    Write-Progress -Activity "Copying files..." -PercentComplete ($i / $total) * 100
}

Progress Bar with Estimated Time:

$remainingSeconds = 600
$progressPercentage = 0
while ($progressPercentage -lt 100) {
    Write-Progress -Activity "Installing updates..." -PercentComplete $progressPercentage -SecondsRemaining $remainingSeconds
    $progressPercentage += 10
    $remainingSeconds -= 60
}

Common Issues

Incorrect Percentage Values: Ensure the -PercentComplete value is between 0 and 100.
Negative Time Remaining: The -SecondsRemaining value should be positive.

Integration

Pipeline Integration: Write-Progress can be used as the last command in a pipeline to display the progress of the preceding commands.
Scheduled Jobs: This command can be integrated into scheduled jobs to provide progress updates via email or other notifications.

  • Start-Job: Starts a background job and creates a Job object.
  • Get-Job: Retrieves information about a running or completed job, including its progress.
  • Stop-Job: Stops a running job.