Skip to content

Do you want an example of Invoke-SpectreCommandWithProgress with ForEach-Object -Parallel? #125

@o-l-a-v

Description

@o-l-a-v

I just thought PwshSpectreConsole might be awesome for outputting progress bars! I got it working with some maths. This might be useful to others too, I can contribute it as an example to the documentation if you want.

With Invoke-SpectreCommandWithProgress:

# Enable UTF8 encoding
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = [System.Text.UTF8Encoding]::new()

# Kick of jobs
$Jobs = 1 .. 117 | ForEach-Object -AsJob -ThrottleLimit 7 -Parallel {
    Start-Sleep -Seconds ($_ % 2 -eq 0 ? 2 : 3)
}

# Show progress
Invoke-SpectreCommandWithProgress -ScriptBlock {
    param (
        [Spectre.Console.ProgressContext] $Context
    )
    $Task = $Context.AddTask('Waiting for jobs to complete')
    do {
        $PercentageComplete = [byte](
            [math]::Round(
                $Jobs.'ChildJobs'.Where{$_.'State' -eq 'Completed'}.'Count' / $Jobs.'ChildJobs'.'Count' * 100,
                0
            )
        )
        if ($PercentageComplete -gt $Task.'Percentage') {
            $Task.Increment($PercentageComplete - $Task.'Percentage')
        }
        if ($Jobs.'State' -eq 'Running') {
            Start-Sleep -Seconds 1
        }
    }
    until ($Jobs.'State' -eq 'Completed')
    $Task.Increment(100 - $Task.'Percentage')
}
20250805-0824-15.6438588.mp4

Just for reference: With Write-Progress:

# Kick of jobs
$Jobs = 1 .. 117 | ForEach-Object -AsJob -ThrottleLimit 7 -Parallel {
    Start-Sleep -Seconds ($_ % 2 -eq 0 ? 2 : 3)
}

# Show progress
do {
    $PercentageComplete = [double](
        $Jobs.ChildJobs.Where{$_.'State' -eq 'Completed'}.'Count' / $Jobs.'ChildJobs'.'Count' * 100
    )
    Write-Progress -Id 1 -Activity 'Waiting for jobs to complete' -Status ('{0}%' -f [math]::Round($PercentageComplete, 2)) -PercentComplete $PercentageComplete
    if ($Jobs.'State' -eq 'Running') {
        Start-Sleep -Seconds 1
    }
}
until ($Jobs.'State' -eq 'Completed')
Write-Progress -Id 1 -Activity 'Waiting for jobs to complete' -Completed
20250805-0825-42.9733203.mp4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions