Private/Invoke-M365GraphRequest.ps1

function Invoke-M365GraphRequest {
    param(
        [Parameter(Mandatory)]
        [string]$AccessToken,
        [Parameter(Mandatory)]
        [string]$Uri,
        [string]$Method = 'GET',
        [switch]$AllPages
    )

    $headers = @{
        'Authorization'    = "Bearer $AccessToken"
        'Content-Type'     = 'application/json'
        'ConsistencyLevel' = 'eventual'
    }

    $allResults = [System.Collections.Generic.List[object]]::new()
    $nextLink = $Uri
    $pageCount = 0

    while ($nextLink) {
        $pageCount++
        $response = Invoke-RestMethod -Uri $nextLink -Headers $headers -Method $Method

        if ($response.value) {
            foreach ($item in $response.value) {
                $allResults.Add($item)
            }
        }
        else {
            return $response
        }

        if ($AllPages -and $response.'@odata.nextLink') {
            $nextLink = $response.'@odata.nextLink'
            if ($pageCount % 10 -eq 0) {
                Write-M365Log " Retrieved $($allResults.Count) items ($pageCount pages)..."
            }
        }
        else {
            $nextLink = $null
        }
    }

    return $allResults
}