Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active July 11, 2023 12:45
Show Gist options
  • Save santisq/aeabfba701841741c3de2da760ef7979 to your computer and use it in GitHub Desktop.
Save santisq/aeabfba701841741c3de2da760ef7979 to your computer and use it in GitHub Desktop.
0..10 | ForEach-Object {
Start-ThreadJob {
Start-Sleep (Get-Random -Maximum 30)
[pscustomobject]@{
Job = $using:_
Result = 'Hello from [Job #{0:D2}]' -f $using:_
}
}
} | Wait-JobWithProgress |
Receive-Job -AutoRemoveJob -Wait | Format-Table -AutoSize
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()]
[int] $TimeOut # In seconds!
)
begin {
$jobs = [List[object]]::new()
if ($withTimeOut = $PSBoundParameters.ContainsKey('TimeOut')) {
$span = [timespan]::FromSeconds($TimeOut)
}
}
process {
$jobs.AddRange($InputObject)
}
end {
$timer = [Stopwatch]::StartNew()
$total = $jobs.Count
$completed = 0.1
while ($jobs.Count) {
if ($withTimeOut -and $timer.Elapsed -gt $span) {
break
}
$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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment