functions/Graph/Invoke-C365GraphQuery.ps1

function Invoke-C365GraphQuery
{
<#
    .SYNOPSIS
        Executes plain Graph queries.
     
    .DESCRIPTION
        Executes plain Graph queries.
        Uses the existing Graph connection.
     
    .PARAMETER Query
        The actual API query to execute, the common url parts can be omitted.
        Example Input:
        'users/meetingroom1@contoso.onmicrosoft.com/calendarView/?startDateTime=2020-03-31&endDateTime=2021-03-31'
     
    .PARAMETER Method
        Default: Get
        What Rest method to use.
     
    .PARAMETER PageSize
        Add a pagesize, in which data is retrieved.
        All pages are retrieved, no matter the size.
     
    .PARAMETER GetResponse
        Get the base response object, rather than its value property.
        Needed for single item responses.
     
    .PARAMETER BetaApi
        Use the Beta Api of MSGraph.
     
    .EXAMPLE
        PS C:\> Invoke-C365GraphQuery -Query $calendarView
         
        Executes a get request against the graph endpoint address stored in $calendarView
#>

    [CmdletBinding()]
    param (
        [string]
        $Query,
        
        [ValidateSet('Get', 'Put', 'Post', 'Delete')]
        [string]
        $Method = 'Get',
        
        [int]
        $PageSize,
        
        [switch]
        $GetResponse,
        
        [switch]
        $BetaApi
    )
    
    begin
    {
        Assert-GraphConnection -Cmdlet $PSCmdlet
    }
    process
    {
        $finalQuery = $Query
        if ($PageSize) { $finalQuery += "&`$top=$PageSize" }
        
        $client = [Microsoft.Graph.PowerShell.Authentication.Helpers.HttpHelpers]::GetGraphHttpClient([Microsoft.Graph.PowerShell.Authentication.GraphSession]::Instance.AuthContext)
        if ($BetaApi) { $finalQuery = $client.BaseAddress.AbsoluteUri.Replace("/v1.0/", "/beta/") + $finalQuery }
        else { $finalQuery = $client.BaseAddress.AbsoluteUri + $finalQuery }
        
        # Get Token
        $task = $client.GetAsync('')
        $task.Wait()
        $response = $task.GetAwaiter().GetResult()
        $headers = @{
            Authorization = $response.RequestMessage.Headers.Authorization
        }
        
        do
        {
            Write-PSFMessage -Level Debug -String 'Invoke-C365GraphQuery.Graph.Execute' -StringValues $finalQuery
            try { $result = Invoke-RestMethod -UseBasicParsing -Method $Method -Uri $finalQuery -Headers $headers -ErrorAction Stop }
            catch { throw }
            if ($GetResponse) { $result }
            else { $result.value }
            if ($result.'@odata.nextLink') { $finalQuery = $result.'@odata.nextLink' }
        }
        while ($result.'@odata.nextLink')
    }
}