GraphAPI PowerShell SDKを使う

2019年12月12日

Office 365 Advent Calendar 2019 – Adventarの11日目です。

「GraphAPIを勉強したいけどC#分からないし、Azure ADアプリ登録も分からない。PowerShellで気軽に使えればいいのに…」という方にぴったりな、GraphAPI SDK PowerShellがリリースされました。これ使えば、AzureADアプリ登録不要、たった3行のコードでGraphAPIを使いだせます。

準備物

  • Office 365 の管理者アカウント
  • 時間(SDKのインストールに20分ほどかかるため。その間は待ち)

手順

1. SDKのダウンロードとインストール

Register-PSRepository -Name GraphPowerShell -SourceLocation https://graphpowershellrepository.azurewebsites.net/nuget 
Install-module Microsoft.Graph.Beta -Repository GraphPowerShell

2. 接続

Connect-Graph -Scopes "User.Read","User.ReadWrite.All","Mail.ReadWrite","Directory.ReadWrite.All","Chat.ReadWrite", "People.Read","Group.Read.All", "Directory.AccessAsUser.All", "Tasks.ReadWrite","Sites.Manage.All"

表示されたコードを記録し、ブラウザで https://microsoft.com/devicelogin にアクセス。コードを入力。

3. APIの利用

例:受信メールを一覧で表示

Get-User  # ユーザーIDを表示
$UserId = "xxx"
Get-UserMessage -UserId $UserId -Filter "contains(subject,'Marketing')" | select sentDateTime, subject 

例:Teamsチャットメッセージを一覧表示

Get-Chat # chatidを特定
$chatId = "xxx"
Get-ChatMessage -chatId $chatId  

「3. APIの利用」で必要な権限を「2. 接続」で指定しないといけないが、それ以外は使い慣れたPowerShellで操作できるので、GraphExplorerから一歩進んだGraphAPIの勉強にはぴったりだと思いました。

参考情報

Posted by tera