Skip to content

Instantly share code, notes, and snippets.

@Juanito99
Created May 3, 2021 20:14
Show Gist options
  • Select an option

  • Save Juanito99/c9a48419959280fec3b12ddc9a5022e2 to your computer and use it in GitHub Desktop.

Select an option

Save Juanito99/c9a48419959280fec3b12ddc9a5022e2 to your computer and use it in GitHub Desktop.
Query Microsoft Graph with PowerShell
# Azure AD OAuth Application Token for Graph API
# Get OAuth token for a AAD Application (returned as $token)
$clientId = "YOUR Client ID"
$tenantId = "YOUR Tenant ID"
$clientSecret = 'YOUR Client Secret'
# Construct URI
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
# Construct Body
$body = @{
client_id = $clientId
scope = "https://graph.microsoft.com/.default"
client_secret = $clientSecret
grant_type = "client_credentials"
}
# Get OAuth 2.0 Token
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing
# Access Token
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token
# Example report querz
$uri = "https://graph.microsoft.com/beta/reports/getSharePointSiteUsageSiteCounts(period='D30')?`$format=application/json"
$query = Invoke-RestMethod -Method Get -Uri $uri -ContentType "application/json" -Headers @{Authorization = "Bearer $token"} -ErrorAction Stop
$query.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment