简体   繁体   English

PowerShell并行API数据检索

[英]PowerShell Parallel API Data Retrieval

I'm trying to create a PowerShell script for retrieving JSON data from a Rest API. 我正在尝试创建PowerShell脚本以从Rest API检索JSON数据。 This script would run as a SQL Server Agent Job, and insert the final data table with everything collected into the database. 该脚本将作为SQL Server代理作业运行,并将最终的数据表以及收集到的所有内容插入数据库中。

I've explored -Parallel option for the Foreach loop, added it to a workflow, but get blocked when trying to write data to the datatable because it seems to be treated differently than just a simple object. 我已经研究了Foreach循环的-Parallel选项,将其添加到工作流中,但是在尝试将数据写入数据表时被​​阻塞,因为它似乎与简单对象不同。

Is this something that could be done with jobs? 这可以通过工作来完成吗? Is there another way I could run this in parallel? 还有另一种方法可以并行运行吗? Does the whole thing need restructured? 整个事情是否需要重组? Ideally this would run in just native PowerShell code without having to install any other modules. 理想情况下,这将仅在本机PowerShell代码中运行,而无需安装任何其他模块。

The basic structure of my code today is: 我今天的代码的基本结构是:

#Compose URL

#Create a New-Object system.Data.DataTable and configure it

#Make Invoke-RestMethod API call to get the collection of objects

Foreach($object in $Collection){
#Make API call for details about each object
#Add data to datatable
}

#Write datatable to database

Why don't you use jobs for this? 您为什么不为此使用工作?

# define script block with api call
$JobSb = {
  param($obid)

  # make api call

  write-output = [PsCustomObject]@{
    Obid = $obid
    ApiResult = 0;
  }
}

# start jobs for all objects
Foreach ($object in $Collection) {
    Start-Job -ScriptBlock $JobSB -ArgumentList $object.Id -Name $object.name
}

# wait for jobs to finish
while (get-job) {
    Get-Job | Where-Object State -NE 'Running' | ForEach-Object {
        if ($_.State -ne 'Completed') {
            Write-Warning ('Job [{0}] [{1}] ended with state [{2}].' -f $_.id,$_.Name,$_.State)
        } else {
            $JobResults = @(Receive-Job $_)
        }

        # write results to datatable

        remove-job $_
    }
    start-sleep -Seconds 1
}

Api calls will be made in parallel. api调用将并行进行。 You may want to control the number of jobs running at the same time if there's a lot of them. 如果有很多作业,则可能需要控制同时运行的作业数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM