Public/Invoke-GraphAPI.ps1
<# .COPYRIGHT Copyright (c) Office Center Hønefoss AS. All rights reserved. Licensed under the MIT license. See https://github.com/officecenter/OCH-Public/blob/master/LICENSE for license information. #> Function Invoke-GraphAPI { <# .SYNOPSIS This function is used to GET or POST to the graph API and capture any exceptions .DESCRIPTION The function connects to the Graph API Interface and tries to complete an action passed as an argument .EXAMPLE Invoke-GraphAPI -Resource groups Returns all groups registered with Azure AD .NOTES NAME: Invoke-GraphAPI #> [cmdletbinding(DefaultParameterSetName = 'GET')] param ( [ValidateSet('v1.0','beta')] [String] $graphApiVersion = 'beta', [Parameter(ParameterSetName = 'BODY', Position = 0, Mandatory = $true)] [Parameter(ParameterSetName = 'GET', Position = 0, Mandatory = $true)] [String] $Resource, [Parameter(ParameterSetName = 'BODY', Mandatory = $true)] [ValidateSet('POST','PATCH')] [String] $Method, [Parameter(ParameterSetName = 'BODY', Mandatory = $true)] [String] $Body ) try { $authToken = Get-AuthToken $uri = "https://graph.microsoft.com/$graphApiVersion/$Resource" If ($PSCmdlet.ParameterSetName -eq 'GET') { (Invoke-RestMethod -Uri $uri -Headers $authToken -Method 'GET').Value } ElseIf ($PSCmdlet.ParameterSetName -eq 'BODY') { (Invoke-RestMethod -Uri $uri -Headers $authToken -Method $Method -Body $Body -ContentType 'application/json').Value } } catch { $ex = $_.Exception $errorResponse = $ex.Response.GetResponseStream() $reader = New-Object -TypeName System.IO.StreamReader -ArgumentList ($errorResponse) $reader.BaseStream.Position = 0 $reader.DiscardBufferedData() $responseBody = $reader.ReadToEnd() Write-Output -Object "Response content:`n$responseBody" -ForegroundColor Red Write-Error -Message "Request to $uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" break } } |