2017-03-23 24 views
0

我加入了一些成果(设备)数组,然后过滤和行动,打击在后面的脚本:Do循环使用REST API显示意想不到的效果

$Devurl = "https://my-site.com/internal/api" 
$restResults = Invoke-RestMethod -uri "$Devurl/$device" -UseDefaultCredentials -Method Get -ContentType "application/json" 

$resultpages = $restResults.Pages 
$incpages = '' 
$testarray = @() 

Do { 
    [int]$incpages += 1 
    $url = ($restResults.nexturl) -replace 'page=1',"page=$incpages" 
    $getresults = Invoke-RestMethod -uri $url -UseDefaultCredentials -Method Get -ContentType "application/json" 
    $testarray += $getresults.Models 
    $resultpages -= 1 
    } while ($resultpages -gt 0) 

我可以这样做:

$testarray | where {$_.os -like '*windows*'} | select hostname,os 

其中一期工程,但我很困惑,为什么这些计数(设备的总数)是不同的:

$testarray.Count 
11434 

$restResults.Count 
11534 

原始$restResults有116页,我添加了验证循环增量从第1页到第116页的代码。

我错过了什么?

回答

1

看起来您似乎忘了将第一页的内容添加到$testarray。当第一次传递do-while-loop时,通过调用$restResults.nextUrl加载第二页,以便跳过第一页。我建议如下调整你的脚本代码:

$devurl = "https://my-site.com/internal/api"; 
$restResults = Invoke-RestMethod -Method Get -uri "$devurl/$device" -UseDefaultCredentials; 

$resultpages = $restResults.Pages; 
$testarray = @(); 
$testarray += $restResults.Models; 

Do { 
    $restResults = Invoke-RestMethod -Method Get -uri $restResults.nexturl -UseDefaultCredentials; 
    $testarray += $restResults.Models; 
    $resultpages -= 1 
} while ($resultpages -gt 0) 
+0

谢谢rufer7,这个技巧! – J1raya