📈

モジュールを使わずに直接 Microsoft Graph API を実行する PowerShell スクリプト

に公開

はじめに

Microsoft Graph API(以降は Graph API)は、Microsoft サービスの設定や情報を取得・更新するための強力なツールです。Graph API を使用することで効率的にデータを操作することが可能になります。

Graph API は多くのプログラミング言語で SDK が提供されており、開発者は自分の得意な言語で簡単に実装を行うことができます。PowerShell 用の Microsoft Graph PowerShell SDK も提供されており、スクリプトを使った自動化や管理が容易になります。

一方で、SDK のバージョンアップや新機能の追加に伴う対応が必要になることもあります。そのため今回はモジュールに依存せず、直接 Graph API を実行する方法について確認していきます。

参考

https://learn.microsoft.com/ja-jp/graph/auth-v2-service?tabs=http

事前準備

今回のスクリプトでは、サービス プリンシパルを使用します。詳細は割愛しますが、事前準備としてアプリの登録とシークレットの作成が必要です。
また、前述の参考 URL を確認し、アプリに Graph API に対するアプリケーションのアクセス許可を追加します。今回はサンプルで条件付きアクセスを取得するため、Policy.Read.All を追加します。

PowerShell スクリプト

# パラメータを指定
$clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$clientSecret = "your_secret"
$scope = "https://graph.microsoft.com/.default" # スコープを指定
$grantType = "client_credentials"


### Bearer トークンを取得 ###############################################
# トークン取得用のエンドポイント
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# リクエストボディを作成
$body = @{
    client_id     = $clientId
    scope         = $scope
    client_secret = $clientSecret
    grant_type    = $grantType
}

# トークンを取得
$response = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $response.access_token

# ヘッダーを作成
$headers = @{
        Authorization = "Bearer $accessToken"
    }


### 条件付きアクセスを取得 ###############################################

# Microsoft Graph API のエンドポイントを指定
$uri = "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies"

# GET リクエストを送信してユーザー情報を取得
$response = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers

# ファイルに保存
$response | ConvertTo-Json -Depth 8 | Out-File -FilePath "C:\temp\conditionalAccess-Policies.json" -Encoding utf8

実行後、以下のように json ファイルとして保存ができます。

補足

他の設定を取得する場合、以下の Graph Explorer でエンドポイントを検索することができます。
https://developer.microsoft.com/en-us/graph/graph-explorer

Microsoft (有志)

Discussion