I'm adding some results (devices) to an array to then filter and action against later in the script:
$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)
I can do something like:
$testarray | where {$_.os -like '*windows*'} | select hostname,os
Which works, however I'm puzzled as to why these counts (the total number of devices) are different:
$testarray.Count
11434
$restResults.Count
11534
The original $restResults
has 116 pages and I've added code to verify the loop increments from page 1 through to page 116.
What am I missing?
It seems like you forgot adding content of first page to the $testarray
. When first passing do-while-loop you load the second page by invoking $restResults.nextUrl
so the first page gets skipped. I suggest to adjust your script code as follows
$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)