PowerShell Script

RESTful HTTP Microsoft Graph without any dependent libraries.

using namespace System.Collections.Generic
$ErrorActionPreference = 'stop'

function Send-MicrosoftGraphRequest {
    [CmdletBinding()]
    [OutputType([List[PSCustomObject]])]
    param
    (
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 0)]
        [String] $Method,
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 1)]
        [String] $GraphUri,
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 2)]
        [String] $BearerToken,
        [Parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            Position = 3)]
        [String] $Body
    )
    process {
        $resultList = [List[PSCustomObject]]::new()
        $headers = @{
            Authorization = "$BearerToken"
        }
        try {
            do {
                Write-Host "--- HTTP $Method Request ---"
                Write-Host $GraphUri
                Write-Host
                switch ($Method.ToLower()) {
                    { ($_ -eq 'post') -or $_ -eq 'put' -or $_ -eq 'patch' } {
                        Write-Host $Body
                        $result = Invoke-RestMethod -Method $Method -Uri $GraphUri `
                         -headers $headers -Body $Body -ContentType 'application/json'
                        break
                    }
                    Default {
                        $result = Invoke-RestMethod -Method $Method -Uri $GraphUri `
                         -headers $headers
                    }
                }
                
                if ($result.Value.Count -eq 0) {
                    $result.PSObject.Properties.Remove('@odata.context')
                    $resultList.Add($result)
                }
                else {
                    $result.Value.ForEach({
                            $resultList.Add($_)
                        })
                    $GraphUri = $result.'@Odata.NextLink'
                }
            } while ($result.'@Odata.NextLink')
        }
        catch {
            Write-Warning $Error[0]
        }
        $resultList
    }
}

# $bearerToken = 'REQUIRED'
$graphVersion = 'https://graph.microsoft.com/beta'
$request = '/me'
$body = ''
Send-MicrosoftGraphRequest GET ($graphVersion + $request) $bearerToken
# Send-MicrosoftGraphRequest POST ($graphVersion + $request) $bearerToken $body
# Send-MicrosoftGraphRequest PUT ($graphVersion + $request) $bearerToken $body
# Send-MicrosoftGraphRequest PATCH ($graphVersion + $request) $bearerToken $body

Categories:

Updated: