Microsoft Graph API Query Collection
This documentation provides a quick-access reference for common Microsoft Graph API queries composed in PowerShell functions. It should be a dynamic place with helpful resources to leverage Microsoft Graph API.
Requirements: Since we use Microsoft Entra ID as IDP, we must already have a Bearer Token with valid Scope. Use this guide to learn more on how to retrieve the right authentication token: Microsoft Graph API | LNC DOCS
Add Entra ID Device to Entra ID Group
# Function to add a device to a group
function Add-DeviceToGroup {
param (
[string]$deviceId,
[string]$groupId
)
$uri = "https://graph.microsoft.com/v1.0/groups/$groupId/members/`$ref"
$body = @{
"@odata.id" = "https://graph.microsoft.com/v1.0/devices/$deviceId"
} | ConvertTo-Json
try {
Invoke-RestMethod -Method POST -Uri $uri -Header @{Authorization = "Bearer $Global:MicrosoftEntraIDAccessToken"; "Content-Type" = "application/json"} -Body $body
Write-Output "Added device $deviceId to group $groupId"
}
catch {
Write-Output "Failed to add device $deviceId to group $groupId : $_"
}
}
Get Primary User of Entra ID Device
# Function to get the primary user of a device
function Get-PrimaryUser {
param (
[string]$deviceId
)
$uri = "https://graph.microsoft.com/v1.0/devices/$deviceId/registeredOwners?`$top=1&`$select=id,displayName,userPrincipalName"
try {
$Result = Invoke-RestMethod -Method GET -Uri $uri -Header @{Authorization = "Bearer $Global:MicrosoftEntraIDAccessToken" }
return $Result.value[0]
}
catch {
Write-Output "Failed to get primary user for device $deviceId : $_" -ForegroundColor Red
return $null
}
}
No Comments