Need to connect to Microsoft Graph with PowerShell? The following PowerShell script does just that (pretty easily)!
So what is Microsoft Graph API?
“Microsoft Graph is a Microsoft developer platform that connects multiple services and devices. Initially released 2015, the Microsoft Graph builds on Office 365 APIs and allows developers to integrate their services with Microsoft products, including Windows, Office 365, and Azure. At its Build 2017 conference, Microsoft announced it would use the Microsoft Graph to bring new functionality and connectivity between Windows and other OS platforms, including Android and iOS.” –Wikipedia
The following script have a function called “Get-GraphAPIAccessToken” (line 127 in the code below) which have two optional options available.
- Credential
- If you don’t want to get an login prompt, when connecting to the API. Then use:
-Credential (Create-PSCredential -Username “admin@contoso.onmicrosoft.com” -Password “AdminPasswordHere”)
- If you don’t want to get an login prompt, when connecting to the API. Then use:
- ClientID
- If you need to use a registered application in Azure AD, specify the application id. Otherwise it will use a well-known value that are registered with Azure AD. An example would be:
-ClientID 3b7e46ca-4495-410f-9691-f90793f0f666
- If you need to use a registered application in Azure AD, specify the application id. Otherwise it will use a well-known value that are registered with Azure AD. An example would be:
There are some requirements before you can run the code, which is:
- You need an valid internet connection (duuuh?!).
- The script leverages AzureRM and the script will try to install it, but if it fails you can use “Install-Module AzureRM -SkipPublisherCheck -AllowClobber -Force -Confirm:$false;” to install it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
#Requires -Version 3.0 <# .SYNOPSIS Connect to Microsoft Graph API. .DESCRIPTION Get an access token from Microsoft Graph API. .PARAMETER .EXAMPLE .NOTES Author: Alex Ø. T. Hansen Date: 11-07-2018 Last Updated: 11-07-2018 #> ################################################ <# Function - Start #> #Create credentials. Function Create-PSCredential { [cmdletbinding()] Param ( [Parameter(Mandatory=$true, HelpMessage="Please provide a valid username, example 'user@contoso.onmicrosoft.com'.")]$Username, [Parameter(Mandatory=$true, HelpMessage="Please provide a valid password, example 'MyPassw0rd!'.")]$Password ) #Convert the password to a secure string. $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force; #Convert $Username and $SecurePassword to a credential object. $Credential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $Username,$SecurePassword #Return the credential object. Return $Credential; } #Get Microsoft Graph API access token. Function Get-GraphAPIAccessToken { [cmdletbinding()] Param ( [Parameter(Mandatory=$false)][PSTypeName('Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential')]$Credential, [Parameter(Mandatory=$false)][string]$ClientID = "1950a258-227b-4e31-a9cf-717495945fc2", [Parameter(Mandatory=$true)][string]$RedirectURI, [Parameter(Mandatory=$true)][string]$ResourceURI, [Parameter(Mandatory=$true)][string]$Authority ) #Retrieves authentication tokens from services and gets address of the authority to issue token. $AuthenticationContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $Authority; #If the credential is set. If($Credential) { #Get token with username and password in $Credential. $AuthenticationResult = $AuthenticationContext.AcquireToken($ResourceURI, $ClientID, $Credential); } Else { #Prompt user for credentials. $AuthenticationResult = $AuthenticationContext.AcquireToken($ResourceURI, $ClientID, $RedirectURI, [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always) } #Return the token. Return $AuthenticationResult.AccessToken; } #Check if the module is installed. Function Check-Module { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)][string]$Name ) #If the module exist. If(Get-Module -ListAvailable -Name $Name) { Return $true; } Else { Return $false; } } <# Functions - End #> ################################################ <# Input - Start #> #URI. $RedirectURI = "urn:ietf:wg:oauth:2.0:oob"; $ResourceURI = "https://graph.microsoft.com"; $Authority = "https://login.microsoftonline.com/common"; <# Input - End #> ################################################ <# Main - Start #> #If the module AzureRM isn't installed. If(!(Check-Module -Name AzureRM)) { Write-Output "Module: Installing 'AzureRM'"; #Install the module. Install-Module AzureRM -SkipPublisherCheck -AllowClobber -Force -Confirm:$false; } Else { Write-Output "Module: 'AzureRM' already installed."; } #Get access token. Write-Output "Token: Getting Microsoft Graph API access token."; $AccessToken = Get-GraphAPIAccessToken -RedirectURI $RedirectURI -ResourceURI $ResourceURI -Authority $Authority; <# Main - End #> ################################################ |
When you have an access token, you can use the following example which gets the current user profile details:
1 2 3 4 5 |
$ApiUrl = "https://graph.microsoft.com/v1.0/me"; $Response = (Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken"} -Uri $ApiUrl -Method Get); #Show reponse. Return ($Response); |
Get the Azure AD users:
1 2 3 4 5 |
$ApiUrl = "https://graph.microsoft.com/v1.0/users" $Users = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken"} -Uri $ApiUrl -Method Get #Show reponse. Return ($Users).Value; |
Send an e-mail (need an Exchange license on the user):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$Recipient = "xyz@contoso.com"; $Body = @" { "message" : { "subject": "E-mail through API", "body" : { "contentType": "Text", "content": "Pretty cool stuff, right?!" }, "toRecipients": [ { "emailAddress" : { "address" : "$Recipient" } } ] } } "@; $ApiUrl = "https://graph.microsoft.com/v1.0/me/sendMail"; Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken"} -Uri $ApiUrl -Method Post -Body $Body -ContentType application/json; |
For more usage examples, Microsoft have create an repository on GitHub.
Hi Alex
Thanks for the very helpful post. Do you know if it is possible to send and get emailmessages without registering an application?
I can get messages in the graph explorer but not in my script.
Your welcome 🙂
I don’t think so currently.
Does this script work with PowerShell 6.1.3?
Should do, try it and report back?