function Send-MicrosoftGraphRequest {
[CmdletBinding()]
param
(
[Parameter(
Mandatory = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0)]
[ValidateSet('GET', 'POST', 'PUT', 'PATCH')]
[String] $Method,
[Parameter(
Mandatory = $true,
ValueFromPipelineByPropertyName = $true,
Position = 1)]
[Uri]
[String] $GraphUri,
[Parameter(
Mandatory = $true,
ValueFromPipelineByPropertyName = $true,
Position = 2)]
[String] $GraphAccessToken,
[Parameter(
Mandatory = $false,
ValueFromPipelineByPropertyName = $true,
Position = 3)]
[String] $Body = $null
)
process {
try {
$headers = @{}
$headers.Add("Authorization", "Bearer $GraphAccessToken")
$headers.Add("Content-Type", "application/json")
if ($Method -ne 'get') {
Invoke-RestMethod -Uri $GraphUri -Method $Method -Headers $headers -Body $Body
}
else {
$resultList = @()
do {
$response = Invoke-RestMethod -Uri $GraphUri -Method GET -Headers $headers
if ($null -eq $response.value -and $response)
{ $resultList += $response } else {
$resultList += $response.value
}
$graphUri = $response.'@odata.nextLink'
} while ($response.'@odata.nextLink')
$resultList
}
}
catch {
if ($_.Exception.GetType().Name -eq 'HttpResponseException') {
Write-Host -ForegroundColor Red "--- HTTP Response Error ---"
$code = (ConvertFrom-Json $_.ErrorDetails.Message).error.code
$message = (ConvertFrom-Json $_.ErrorDetails.Message).error.message
Write-Host -ForegroundColor Red "Code:$code"
Write-Host -ForegroundColor Red "Message:$message"
Write-Host
}
throw $_
}
}
}
# $graphAccessToken = 'ey...'
$graphBase = 'https://graph.microsoft.com/'
$graphVersion = 'v1.0' # or beta
$resource = '/me'
$graphUri = $graphBase + $graphVersion + $resource
$body = ''
Send-MicrosoftGraphRequest GET $graphUri $graphAccessToken
# Send-MicrosoftGraphRequest POST $graphUri $GraphAccessToken $body
# Send-MicrosoftGraphRequest PUT $graphUri $GraphAccessToken $body
# Send-MicrosoftGraphRequest PATCH $graphUri $GraphAccessToken $body