Add Write-Progress to Get-Job/Wait-Job

Wait-Job -Timeout 120 will block the thread until the specified timeout or all jobs have completed, hence, is not possible to display progress and wait for them at the same time.

There are 2 alternatives that I can think of, the first one would be to create a proxy command / proxy function around this cmdlet to extend it’s functionality.

These blogs demonstrate how to do it:

You can also follow the indications from this helpful answer.


The other alternative is to define your own function that does a similar work as Wait-Job but, instead of blocking the thread, you can add a loop that will run based on 2 conditions:

  • That the elapsed time is lower than or equal to the Timeout we passed as argument to the function (we can use Diagnostics.Stopwatch for this).
  • And, that the jobs are still Running (the $jobs List<T> is still populated).

Note, the function below should work in most cases however is purely for demonstration purposes only and should not be relied upon.

First we define a new function that can be used to display progress as well as wait for our jobs based on a timeout:

using namespace System.Collections.Generic
using namespace System.Diagnostics
using namespace System.Threading
using namespace System.Management.Automation

function Wait-JobWithProgress {
    [cmdletbinding()]
    param(
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]] $InputObject,

        [parameter()]
        [double] $TimeOut
    )

    begin {
        $jobs = [List[object]]::new()
    }

    process {
        foreach($job in $InputObject) {
            $jobs.Add($job)
        }
    }

    end {
        $timer      = [Stopwatch]::StartNew()
        $total      = $jobs.Count
        $completed  = 0.1
        $expression = { $true }

        if($PSBoundParameters.ContainsKey('TimeOut')) {
            $expression = { $timer.Elapsed.TotalSeconds -le $TimeOut }
        }

        while((& $expression) -and $jobs) {
            $remaining = $total - $completed
            $average   = $timer.Elapsed.TotalSeconds / $completed
            $estimate  = [math]::Round($remaining * $average)
            $status="Completed Jobs: {0:0} of {1}" -f $completed, $total
            $progress  = @{
                Activity         = 'Waiting for Jobs'
                PercentComplete  = $completed / $total * 100
                Status           = $status
                SecondsRemaining = $estimate
            }
            Write-Progress @progress

            $id = [WaitHandle]::WaitAny($jobs.Finished, 200)
            if($id -eq [WaitHandle]::WaitTimeout) {
                continue
            }

            # output this job
            $jobs[$id]
            # remove this job
            $jobs.RemoveAt($id)
            $completed++
        }

        # Stop the jobs not yet Completed and remove them
        $jobs | Stop-Job -PassThru | ForEach-Object {
            Remove-Job -Job $_
            "Job [#{0} - {1}] did not complete on time and was removed." -f $_.Id, $_.Name
        } | Write-Warning
        Write-Progress @progress -Completed
    }
}

Then for testing it, we can create a few jobs with a random timer:

0..10 | ForEach-Object {
    Start-Job {
        Start-Sleep (Get-Random -Minimum 5 -Maximum 15)
        [pscustomobject]@{
            Job    = $using:_
            Result="Hello from [Job #{0:D2}]" -f $using:_
        }
    }
} | Wait-JobWithProgress -TimeOut 10 |
Receive-Job -AutoRemoveJob -Wait | Format-Table -AutoSize

Leave a Comment