Office365 Graph API抓取使用情況報告

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
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章