Graph API | Function to retrieve data until all is retrieved
If you do a Graph API request you will get the first 999 results. But what if there are more pages for example or more information to retrieve?
I wrote a function to use for that. Also is it possible that the token will expire. In the function we will check if the token is still valid and otherwise will renew so the results will always be retrieved.
The function as written below is based on multiple posts on this website. You can find for example de connectionDetails in a post where also an app registration was created (here).
Function RunQueryAndProcess
function RunQueryAndProcess {
Try {
$Results = (Invoke-RestMethod -Headers $header -Uri $url -Method Get)
}
catch {
$webError = $_
$mustRetry = 1
}
# if token is expired renew token
If ($mustRetry -and ($weberror.ErrorDetails.message -like "*Access token has expired or is not yet valid.*")) {
#region connection
# Get an access token for the Microsoft Graph API
do {
Try {
$accessToken = (Get-MSALToken -Clientid $ConnectionDetails.ClientId -ClientSecret $connectionDetails.ClientSecret -TenantId $ConnectionDetails.TenantId -ForceRefresh).AccessToken
$header = @{
'Authorization' = "BEARER $accesstoken"
'Content-type' = "application/json"
}
}
Catch {
write-host "Unable to acquire access token, check the parameters are correct`n$($Error[0])"
exit
}
Start-Sleep -seconds 2
} while (
$AccessToken -eq $null
)
#endregion connection
$Results = (Invoke-RestMethod -Headers $header -Uri $url -Method Get)
}
#Output Results for Debugging
#write-host $results
#Begin populating results
[array]$ResultsValue = $Results.value
#If there is a next page, query the next page until there are no more pages and append results to existing set
if ($results."@odata.nextLink" -ne $null) {
$NextPageUri = $results."@odata.nextLink"
##While there is a next page, query it and loop, append results
While ($NextPageUri -ne $null) {
$NextPageRequest = (Invoke-RestMethod -Headers $header -Uri $NextPageURI -Method Get)
$NxtPageData = $NextPageRequest.Value
$NextPageUri = $NextPageRequest."@odata.nextLink"
$ResultsValue = $ResultsValue + $NxtPageData
}
}
##Return completed results
return $ResultsValue
}
How to use
# set url from graph api to retrieve
$url = [GRAPH API URL]
# add results to a variable
$variable = RunQueryAndProcess
The results of the Graph API request will be set to the variable to use later.