Skip to content

Instantly share code, notes, and snippets.

@vdepagter
Created December 29, 2023 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdepagter/f3edcefb405b7ed296e21aaa7afc5e28 to your computer and use it in GitHub Desktop.
Save vdepagter/f3edcefb405b7ed296e21aaa7afc5e28 to your computer and use it in GitHub Desktop.
Get-MgGraphAllPages.ps1
# Source: David Richmond, https://dev.to/celadin/get-mggraphallpages-the-mggraph-missing-command-45b5
function Get-MgGraphAllPages {
[CmdletBinding(
ConfirmImpact = 'Medium',
DefaultParameterSetName = 'SearchResult'
)]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'NextLink', ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[Alias('@odata.nextLink')]
[string]$NextLink
,
[Parameter(Mandatory = $true, ParameterSetName = 'SearchResult', ValueFromPipeline = $true)]
[ValidateNotNull()]
[PSObject]$SearchResult
,
[Parameter(Mandatory = $false)]
[switch]$ToPSCustomObject
)
begin {}
process {
if ($PSCmdlet.ParameterSetName -eq 'SearchResult') {
# Set the current page to the search result provided
$page = $SearchResult
# Extract the NextLink
$currentNextLink = $page.'@odata.nextLink'
# We know this is a wrapper object if it has an "@odata.context" property
#if (Get-Member -InputObject $page -Name '@odata.context' -Membertype Properties) {
# MgGraph update - MgGraph returns hashtables, and almost always includes .context
# instead, let's check for nextlinks specifically as a hashtable key
if ($page.ContainsKey('@odata.count')) {
Write-Verbose "First page value count: $($Page.'@odata.count')"
}
if ($page.ContainsKey('@odata.nextLink') -or $page.ContainsKey('value')) {
$values = $page.value
} else { # this will probably never fire anymore, but maybe.
$values = $page
}
# Output the values
# Default returned objects are hashtables, so this makes for easy pscustomobject conversion on demand
if ($values) {
if ($ToPSCustomObject) {
$values | ForEach-Object {[pscustomobject]$_}
} else {
$values | Write-Output
}
}
}
while (-Not ([string]::IsNullOrWhiteSpace($currentNextLink)))
{
# Make the call to get the next page
try {
$page = Invoke-MgGraphRequest -Uri $currentNextLink -Method GET
} catch {
throw $_
}
# Extract the NextLink
$currentNextLink = $page.'@odata.nextLink'
# Output the items in the page
$values = $page.value
if ($page.ContainsKey('@odata.count')) {
Write-Verbose "Current page value count: $($Page.'@odata.count')"
}
# Default returned objects are hashtables, so this makes for easy pscustomobject conversion on demand
if ($ToPSCustomObject) {
$values | ForEach-Object {[pscustomobject]$_}
} else {
$values | Write-Output
}
}
}
end {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment