3

我有一个查询更改的 URL。查询存储在一个数组中,因此在循环中更改 URL 不是问题(我对任何特定查询都不感兴趣)。

我很难为每个 URL 创建作业并同时启动一组作业并监视它们。

我想开始一次遍历 5 个查询数组,我将调用 5 个新 URL,因此每次迭代都需要一个作业数组,其元素是该迭代的 URL。

我的做法对吗?任何指针将不胜感激!

这是演示我的方法的示例代码:

$queries = 1..10
$jobs = @()

foreach ($i in $queries) {
  if ($jobs.Count -lt 5) {
     $ScriptBlock = { 
        $query = $queries[$i]
        $path = "http://mywebsite.com/$query"
        Invoke-WebRequest -Uri $path
     }
     $jobs += Start-Job -ScriptBlock $ScriptBlock
  } else {
      $jobs | Wait-Job -Any
  }
}
4

1 回答 1

2

You will run into a couple of issues with the code above. The scriptblock gets transferred to a different PowerShell.exe process to execute so it won't have acess to $queries. You will to pass that it like so:

...
$scriptblock = {param($queries)
    ...
}
...
$jobs += Start-Job $scriptblock -Arg $queries

The other issue is that you never remove a completed job from $job so once this $jobs.Count -lt 5 expression evals to false because the count has reached 5, you'll never add anymore jobs. Try something like this:

$jobs | Wait-Job -Any
$jobs = $jobs | Where ($_.State -eq 'Running'}

Then you'll wind up with only the running jobs in $jobs which will allow you to start more jobs as previous jobs complete (or fail).

于 2013-05-27T18:52:25.890 回答