Do loop using rest api 显示意外结果
Do loop using rest api showing unexpected results
我正在将一些结果(设备)添加到一个数组中,以便稍后在脚本中进行过滤和操作:
$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 页的循环增量。
我错过了什么?
您似乎忘记将第一页的内容添加到 $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)
我正在将一些结果(设备)添加到一个数组中,以便稍后在脚本中进行过滤和操作:
$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 页的循环增量。
我错过了什么?
您似乎忘记将第一页的内容添加到 $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)