'how to automatically update the count of background jobs running in powershell?
I have few background jobs running in powershell and i'm trying to find a way to get the count of jobs "Running" and "Completed" which updates automatically once the job is completed.
function jobDetails {
$d = Get-Job | Measure-Object -Property Name
Write-Output "Total Number of Jobs = " $d.Count
$d = (Get-Job -State Running)
Write-Output "Number of Jobs Running = " $d.count
$d = (Get-Job -State Completed)
Write-Output "Number of Jobs Completed = " $d.count
}
please help me out as I'm a newbie to coding
Solution 1:[1]
Here you have something simple for you to experiment, there are many ways of doing it.
# How many Jobs?
$testJobs = 5
$jobs = 1..$testJobs | ForEach-Object {
Start-Job {
'Hello from Job {0}' -f $using:_
# Set a Random timer between 5 and 10 seconds
Start-Sleep ([random]::new().Next(5,10))
}
}
while($jobs.State -contains 'Running')
{
Clear-Host
"Total Jobs {0}" -f $jobs.Count
"Jobs Running {0}" -f ($jobs.State -eq 'Running').Count
"Jobs Completed {0}" -f ($jobs.State -eq 'Completed').Count
Start-Sleep -Seconds 1
}
Clear-Host
$jobs | Receive-Job -Wait -AutoRemoveJob
You could also use Write-Progress
:
while($jobs.State -contains 'Running')
{
$total = $jobs.Count
$running = ($jobs.State -eq 'Running').Count
$completed = ($jobs.State -eq 'Completed').Count
$progress = @{
Activity = 'Waiting for Jobs'
Status = 'Remaining Jobs {0} of {1}' -f $running, $total
PercentComplete = $completed / $total * 100
}
Write-Progress @progress
Start-Sleep 1
}
This answer shows a similar, more developed alternative, using a function to wait for Jobs with progress and a optional TimeOut parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |