Office365 Graph API grab Usage Report

1. Use the global administrator to log in to Office365 Azure AD to register the Graph API Application. For details, please refer to the official website link https://docs.microsoft.com/zh-cn/graph/auth-register-app-v2
2. Add delegated application Reports.Read.All in API permission
3. In the certificate and client, create the client password
4. Generate Token function

function Graph_Auth
{
$clientID = "Client ID(36 Position)" 
$tenantName = "tenant.onmicrosoft.com"  
$ClientSecret = "Client password"
$Username = "Account with application permission"
$Password = "Above account password"
$ReqTokenBody = @{
    Grant_Type    = "Password"
    client_Id     = $clientID
    Client_Secret = $clientSecret
    Username      = $Username
    Password      = $Password
    Scope         = "https://graph.microsoft.com/.default"
} 
$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
$headerParams = @{
"Content-Type" = "application/json"
"Authorization"="$($TokenResponse.token_type) $($TokenResponse.access_token)"}
return $headerParams
}

5. If the invoke restmethod fails to connect to the server when running, it may be an https certificate problem. Run the following function to ignore the certificate

function Ignore-SelfSignedCerts {
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}}
"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}

6. Grab the relevant usage report and output the file to the current directory where the script runs

Ignore-SelfSignedCerts 
$current_path = Split-Path -Parent $MyInvocation.MyCommand.Definition #Get current directory location
$today = get-date -format yyyy-MM-dd
$headerParams = Graph_Auth       #Use the function in step 4 to generate Token
$detailreports = "getEmailActivityUserDetail","getMailboxUsageDetail","getOffice365ActiveUserDetail"
foreach($detailreport in $detailreports){
Write-Host $detailreport -ForegroundColor Green
$filename = $current_path + "\" + $detailreport+ "_$today.csv"
$url = "https://graph.microsoft.com/v1.0/reports/$detailreport(period='D90')" 
$myReport = ""
$Error.Clear()
$myReport =Invoke-RestMethod -UseBasicParsing -Headers $headerParams -Uri $url -Method Get -Verbose
if($myReport){
$myReport | Out-File $filename -Encoding UTF8
}
}

Tags: Windows JSON encoding

Posted on Wed, 18 Mar 2020 10:13:48 -0400 by pelleas