写入进度条直到Get-Job返回“运行”PowerShell

时间:2013-04-01 08:13:07

标签: arrays powershell

我有一套正在运行的工作。

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...

我想要一个进度条显示,直到作业运行,并且应该说当作业状态在powershell中“完成”时已完成

2 个答案:

答案 0 :(得分:4)

使用Write-Progress作为进度条。使用Get-Job接收当前作业的数量。像这样,

# 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
}

答案 1 :(得分:1)

在while块中使用以下内容以在进度条中显示值

while($runningjobs -gt 0) {
# Update progress based on how many jobs are done yet.
$percent=[math]::Round((($total-$runningjobs)/$total * 100),2)
write-progress -activity "Starting Provisioning Modules Instances" -status "Progress: $percent%" -percentcomplete (($total-$runningjobs)/$total*100)

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