Skip to content

GreyCorbel/GraphHelper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GraphHelper

PowerShell module that provides a robust, production-ready wrapper around the Microsoft Graph API. It handles authentication token acquisition, automatic pagination, throttling retries, large file uploads, and optional Application Insights telemetry — so callers can focus on business logic rather than HTTP plumbing.

Dependencies

Module Purpose
AadAuthenticationFactory Obtains Azure AD access tokens (supports managed identity, service principal, interactive, etc.)
AiLogger Optional Application Insights telemetry logging

Install dependencies from the PowerShell Gallery before using this module:

Install-Module -Name AadAuthenticationFactory
Install-Module -Name AiLogger          # optional, only needed for telemetry
Install-Module -Name GraphHelper

Quick Start

1. Configure authentication

Use AadAuthenticationFactory to create and register an authentication factory, then point GraphHelper at it:

# Create a factory that uses a managed identity (e.g. in Azure Automation / Azure Functions)
New-AadAuthenticationFactory -Name 'ManagedIdentity' -UseManagedIdentity

# Tell GraphHelper which factory to use
Set-GraphAadFactory -Name 'ManagedIdentity'

2. Read data

# Retrieve a single user — returns the user object directly
Get-GraphData -RequestUri '/users/john.doe@contoso.com'

# Retrieve all users — automatically pages through all result pages
$users = Get-GraphData -RequestUri '/users?$select=displayName,userPrincipalName,mail'
$users | Select-Object displayName, mail

3. Write data

# Create a new security group
$body = @{
    displayName     = 'Finance Team'
    mailEnabled     = $false
    mailNickname    = 'finance-team'
    securityEnabled = $true
} | ConvertTo-Json

Invoke-GraphWithRetry -RequestUri '/groups' -Method Post -Body $body

# Update a user's job title
$patch = @{ jobTitle = 'Senior Engineer' } | ConvertTo-Json
Invoke-GraphWithRetry -RequestUri '/users/john.doe@contoso.com' -Method Patch -Body $patch

# Delete a group
Invoke-GraphWithRetry -RequestUri "/groups/$groupId" -Method Delete

Commands

Set-GraphAadFactory

Registers which AadAuthenticationFactory factory name to use for token acquisition.

Set-GraphAadFactory -Name 'ManagedIdentity'

Set-GraphScopes

Overrides the OAuth2 scope used when requesting tokens. The default (https://graph.microsoft.com/.default) covers all permissions granted to the application.

# Use default application permissions (recommended for service accounts / managed identity)
Set-GraphScopes -Scopes 'https://graph.microsoft.com/.default'

Set-GraphBaseUri

Sets the base URI prepended to relative request paths. Defaults to https://graph.microsoft.com/v1.0. Change this to target sovereign clouds or the beta endpoint.

# US Government cloud
Set-GraphBaseUri -BaseUri 'https://graph.microsoft.us/v1.0'

# Beta endpoint
Set-GraphBaseUri -BaseUri 'https://graph.microsoft.com/beta'

Get-GraphData

Issues a GET request and automatically follows all @odata.nextLink pages, returning the complete dataset.

# All members of a group (handles pages transparently)
$members = Get-GraphData -RequestUri "/groups/$groupId/members"

# Advanced query with ConsistencyLevel header
$guests = Get-GraphData `
    -RequestUri '/users?$filter=userType eq ''Guest''&$count=true' `
    -AdditionalHeaders @{ ConsistencyLevel = 'eventual' }

Invoke-GraphWithRetry

Issues any HTTP method against Graph. Automatically retries on HTTP 429 (throttling) using the Retry-After header, up to 100 times.

# Send a Teams chat message
$body = @{
    body = @{ content = 'Hello from GraphHelper!' }
} | ConvertTo-Json -Depth 5

Invoke-GraphWithRetry `
    -RequestUri "/chats/$chatId/messages" `
    -Method Post `
    -Body $body

Add-GraphLargeFile

Uploads a local file of any size to OneDrive or SharePoint using Graph's resumable upload session protocol (5 MB chunks). Existing files are replaced automatically.

# Upload a report to the current user's OneDrive
Add-GraphLargeFile `
    -LocalFilePath 'C:\Reports\annual-report.xlsx' `
    -GraphFilePath '/me/drive/root:/Reports/annual-report.xlsx' `
    -Verbose

# Upload to a SharePoint document library
Add-GraphLargeFile `
    -LocalFilePath 'C:\Videos\onboarding.mp4' `
    -GraphFilePath "/sites/$siteId/drive/root:/Training/onboarding.mp4"

Get-GraphAuthorizationHeader

Returns a hashtable containing the Authorization: Bearer <token> header. Primarily used internally, but useful when you need to call a Graph endpoint with your own Invoke-RestMethod.

$headers = Get-GraphAuthorizationHeader
Invoke-RestMethod -Uri 'https://graph.microsoft.com/v1.0/me' -Headers $headers

Set-GraphAiLogger

Attaches an AiLogger instance for Application Insights telemetry. All Graph calls will emit dependency telemetry under the configured operation name.

$logger = Connect-AiLogger -ConnectionString '<your-connection-string>'
Set-GraphAiLogger -Logger $logger

Notes

  • Relative URIs are supported everywhere — the configured BaseUri is automatically prepended to any path that does not start with http.
  • Pagination is handled transparently by Get-GraphData. Use Invoke-GraphWithRetry when you need only a single page.
  • Throttle protectionInvoke-GraphWithRetry honours the Retry-After response header and backs off accordingly.
  • Only PowerShell Core (CompatiblePSEditions = Core) is supported.

About

Simple module for working with MS Graph API

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors