Public/Get-pseGraphAPIToken.ps1
function Get-pseGraphAPIToken { <# .SYNOPSIS Retrieves an access token for Microsoft Graph API using client credentials. .DESCRIPTION This function retrieves an access token for Microsoft Graph API using client credentials. It requires the Client ID, Client Secret, and Tenant ID. This access token can be used to authenticate requests to Microsoft Graph API. .PARAMETER ClientId Specifies the Client ID (Application ID) of the Azure AD application configured to access Microsoft Graph API. This parameter is mandatory. .PARAMETER ClientSecret Specifies the Client Secret of the Azure AD application configured to access Microsoft Graph API. This parameter is mandatory. .PARAMETER TenantId Specifies the Tenant ID (Directory ID) of the Azure AD tenant associated with the Azure AD application. This parameter is mandatory. .EXAMPLE Get-pseGraphAPIToken -ClientId "your_client_id" -ClientSecret "your_client_secret" -TenantId "your_tenant_id" Retrieve an access token for Microsoft Graph API using client credentials. .NOTES Author: owen.heaume Version: 1.0.0 - Intial release #> [cmdletbinding()] param( [parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [string]$ClientId, [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string]$ClientSecret, [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string]$TenantId ) $body = @{ grant_type = "client_credentials" scope = "https://graph.microsoft.com/.default" client_id = $clientId client_secret = $clientSecret } try { $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Body $body -ea Stop -UseBasicParsing return $tokenResponse.access_token } catch{ write-error "Error: $($_.Exception.Message)" } } |