Powershell – Write Progress Bar till Get-Job Return “Running” PowerShell

arrayspowershell

i have a set of job's which are running.

PS C:\vinith> Get-Job

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
2      scvmm2012-vin   BackgroundJob   Running       True            localhost            Param...
4      scom2012sp1-vin BackgroundJob   Running       True            localhost            Param...
6      scorch2012-vin  BackgroundJob   Running       True            localhost            Param...
8      scsm2012sp1-vin BackgroundJob   Running       True            localhost            Param...
10     spfoundation    BackgroundJob   Running       True            localhost            Param...

I want a progress bar display till the jobs are running and should say completed when the job state becomes "completed" in powershell

Best Answer

Use Write-Progress for the progress bar. Use Get-Job to receive number of current jobs. Like so,

# Some dummy jobs for illustration purposes
start-job -ScriptBlock { start-sleep -Seconds 5 }
start-job -ScriptBlock { start-sleep -Seconds 10 }
start-job -ScriptBlock { start-sleep -Seconds 15 }
start-job -ScriptBlock { start-sleep -Seconds 20 }
start-job -ScriptBlock { start-sleep -Seconds 25 }

# Get all the running jobs
$jobs = get-job | ? { $_.state -eq "running" }
$total = $jobs.count
$runningjobs = $jobs.count

# Loop while there are running jobs
while($runningjobs -gt 0) {
    # Update progress based on how many jobs are done yet.
    write-progress -activity "Events" -status "Progress:" `
   -percentcomplete (($total-$runningjobs)/$total*100)

    # After updating the progress bar, get current job count
    $runningjobs = (get-job | ? { $_.state -eq "running" }).Count
}
Related Topic