azurepowershellpaginationmicrosoft-graph-apimicrosoft-graph-intune

MS Graph API - How to query additional pages


I'm unsure as to how to query additional pages. Through some guides I've seen I've cobbled together the following but am only getting the first 1000 results (expecting a number close to 15000). I seem unable to capture the @odata.nextLink value to add to the loop.

$DeviceList = @()    
$URI = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?`$filter=contains(OperatingSystem,'iOS')&?`$select=serialNumber,Id"

if ($Null -ne $URI) 
    {
    $GetDevices = Invoke-RestMethod -Headers $Headers -Uri $URI
    $DeviceList += $GetDevices.value
    $URI = $GetDevices.'@Odata.nextLink'
    }

$DeviceList | Export-Csv C:\Users\######\Downloads\Test.csv -Force -Append

Solution

  • To handle paging you can use a do loop re-assigning the value of $uri.'@odata.nextLink' to a variable and the loop break condition can be while there is a nextLink:

    & {
        $uri = 'htts://graph.microsoft.com/.....'
    
        do {
            $uri = Invoke-RestMethod -Headers $Headers -Uri $uri
            $uri.Value
            $uri = $uri.'@Odata.nextLink'
        } while($uri)
    } | Export-Csv path\to\export.csv -NoTypeInformation