Office365GraphAPI.psm1
<#
.Synopsis Get a oAuth token to access Microsoft Graph API (Both support WW AND Gallatin) .DESCRIPTION Get a oAuth token to access Microsoft Graph API. Token will be valid for 2 hours. .EXAMPLE Get-Office365Token -AADTenant "modtsp.partner.onmschina.cn" -ClientId "8fad9a3d-ce06-4d85-8f9a-873164f0cafc" -Credential (Get-Credential) .NOTES Developed by Ares Chen .LINK http://graph.microsoft.io/ #> function Get-Office365Token{ param ( [Parameter(Mandatory=$true)] [String] $AADTenant, [Parameter(Mandatory=$true)] [String] $ClientId, [Parameter(Mandatory=$true)] [PSCredential] $Credential, [Parameter(Mandatory=$false)] [bool]$IsGallatin = $true ) $resourceAppIdURI = "https://graph.microsoft.com" $authority = "https://login.windows.net/$aadTenant" if ($IsGallatin) { $resourceAppIdURI ="https://microsoftgraph.chinacloudapi.cn" $authority ="https://login.chinacloudapi.cn/common/oauth2/authorize" } $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority $uc = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential -ArgumentList $Credential.Username,$Credential.Password $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$uc) return $authResult } <# .Synopsis Invoke a request to the Microsoft Graph API(Both support WW AND Gallatin) .DESCRIPTION Invoke a request to the Microsoft Graph API using the Token .EXAMPLE $Token = Get-Office365Token -AADTenant "modtsp.partner.onmschina.cn" -ClientId "8fad9a3d-ce06-4d85-8f9a-873164f0cafc" -Credential (Get-Credential) Invoke-Office365GraphRequest -url "https://microsoftgraph.chinacloudapi.cn/v1.0/me" -Token $Token -Method GET .NOTES Developed by Ares Chen .LINK http://graph.microsoft.io/ #> function Invoke-Office365GraphRequest(){ param($Token, $url, $Method, $Body,$contentType="application/json",$file) try { $headers = @{} $headers.Add('Authorization','Bearer ' + $Token.AccessToken) $headers.Add('Content-Type', $contentType) if($Body) { $response = Invoke-WebRequest -Uri $url -Method $Method -Body $Body -Headers $headers -UseBasicParsing } elseif($file){ $response = Invoke-WebRequest -Uri $url -Method $Method -InFile $file -Headers $headers -UseBasicParsing } else { $response = Invoke-WebRequest -Uri $url -Method $Method -Headers $headers -UseBasicParsing } return (ConvertFrom-Json $response.Content) } catch { #throw ($error[0].Exception.Response) if($_.Exception.Response) { $result = $_.Exception.Response.GetResponseStream() $reader = New-Object System.IO.StreamReader($result) $responseBody = $reader.ReadToEnd(); throw "Status: A system exception was caught.`n $responsebody" } else { throw $_ } } } |