Skip to content

Instantly share code, notes, and snippets.

@andyrobbins
Created April 22, 2024 19:05
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 andyrobbins/cec4c3192e960bf277e96352b971eb08 to your computer and use it in GitHub Desktop.
Save andyrobbins/cec4c3192e960bf277e96352b971eb08 to your computer and use it in GitHub Desktop.
Function Get-AllEntraDevices {
<#
.SYNOPSIS
Retrieves all JSON-formatted Entra device objects using the MS Graph API
Author: Andy Robbins (@_wald0)
License: GPLv3
Required Dependencies: None
.DESCRIPTION
Retrieves all JSON-formatted Entra device objects using the MS Graph API
.PARAMETER Token
The MS Graph-scoped JWT for the user with read access to Entra device
.EXAMPLE
C:\PS> $EntraDevices = Get-AllEntraDevices -Token $Token -ShowProgress
Description
-----------
Uses the JWT in the $Token variable to list all devices and put them into the $EntraDevices variable
.LINK
https://learn.microsoft.com/en-us/graph/api/device-list?view=graph-rest-1.0&tabs=http
#>
[CmdletBinding()] Param (
[Parameter(
Mandatory = $True,
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True
)]
[String]
$Token,
[Parameter(
Mandatory = $False
)]
[Switch]
$ShowProgress = $False
)
# Get all devices
$URI = "https://graph.microsoft.com/beta/devices/?`$count=true"
$Results = $null
$DeviceObjects = $null
If ($ShowProgress) {
Write-Progress -Activity "Enumerating Devices" -Status "Initial request..."
}
do {
$Results = Invoke-RestMethod `
-Headers @{
Authorization = "Bearer $($Token)"
ConsistencyLevel = "eventual"
} `
-URI $URI `
-UseBasicParsing `
-Method "GET" `
-ContentType "application/json"
if ($Results.'@odata.count') {
$TotalDeviceCount = $Results.'@odata.count'
}
if ($Results.value) {
$DeviceObjects += $Results.value
} else {
$DeviceObjects += $Results
}
$uri = $Results.'@odata.nextlink'
If ($ShowProgress) {
$PercentComplete = ([Int32](($DeviceObjects.count/$TotalDeviceCount)*100))
Write-Progress -Activity "Enumerating Devices" -Status "$($PercentComplete)% complete [$($DeviceObjects.count) of $($TotalDeviceCount)]" -PercentComplete $PercentComplete
}
} until (!($uri))
$DeviceObjects
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment