1,使用全局管理员登录Office365 Azure AD注册Graph API应用,具体参考官网链接https://docs.microsoft.com/zh-cn/graph/auth-register-app-v2
2,在API权限添加委托应用Reports.Read.All
3,在证书和客户端,创建客户端密码
4,生成Token函数

function Graph_Auth
{
$clientID = "客户端ID(36位)" 
$tenantName = "tenant.onmicrosoft.com"  
$ClientSecret = "客户端密码"
$Username = "拥有应用权限的账号"
$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,如果invoke-restmethod运行时报无法连接到服务器错误,可能是https证书问题,运行以下函数忽略证书
Office365 Graph API抓取使用情况报告

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,抓取相关使用情况报告并输出文件到脚本运行的当前目录

Ignore-SelfSignedCerts 
$current_path = Split-Path -Parent $MyInvocation.MyCommand.Definition #获取当前目录位置
$today = get-date -format yyyy-MM-dd
$headerParams = Graph_Auth       #使用步骤4的函数生成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
}
}