首页 > 解决方案 > 在 PowerShell 中使用 Microsoft Graph API 获取 Planner 任务

问题描述

我正在尝试将 Microsoft Graph API 与应用程序注册和权限一起使用来修改 Planner 任务。我已成功注册我的应用程序并将权限设置为 (Directory.Read.All, Directory.ReadWrite.All, Group.Read.All, Group.ReadWrite.All, GroupMember.Read.All, GroupMember.ReadWrite.All, User.Read )。但我无法为任何组提取计划我总是得到错误:

> Invoke-RestMethod : {   "error": {
>     "code": "UnknownError",
>     "message": "UserDeleted",
>     "innerError": {
>       "request-id": "043b140e-aa18-42aa-8672-7c164277553f",
>       "date": "2020-05-16T22:47:10"
>     }   } } At C:\Users\jlamb\Scripts\Connect-MicrosoftGraph.ps1:36 char:17
> + ... $Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri ...
> +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>     + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
> WebException
>     + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

我不明白这个错误是什么意思。这是我的示例代码:

$tenant = '67a80b53-1b4f-4278-b269-xxxxxxxxxxxx' #Directory ID
$client_id = 'da398f63-3b2b-4dc3-b594-54cbc0a2924f' #Application ID
$scope = 'https://graph.microsoft.com/.default'
$client_secret = 'xxxxx-xxxx.xxxxxxx.xxxxxxxxxxx.xxx' #PowerShellPOC, expires 5/16/2021
$grant_type = 'client_credentials'

if (-not $headers) {
    $body = @{client_id=$client_id; scope=$scope; client_secret=$client_secret; grant_type=$grant_type}

    $uri = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token"

    $Response = Invoke-RestMethod -Method Post -Uri $uri -Body $body
    $access_token = $Response.access_token

    $headers = @{
        Authorization = "$($Response.token_type) $($Response.access_token)"
        ExpiresOn = $($Response.expires_in)
    }
}


Write-Host "Getting Groups"
$uri = "https://graph.microsoft.com/v1.0/groups?$orderby=displayName"
$Response = $null
$Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri
$Response.value |ft id, displayName
#this works and returns 100 groups

foreach ($groupId in $($Response.value.id)) {
    $groupId
    $uri = "https://graph.microsoft.com/v1.0/groups/$groupId/planner/plans"
    $Response = $null
    $Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri 
    $Response.value |ft
}

我还尝试从我知道存在的计划中提取任务:

$plan_id = 'zBgxnzXTNEaGeW9Hz1CVSmQAHpg2'
$uri = "https://graph.microsoft.com/v1.0/planner/plans/$plan_id/tasks"
$uri
$Response = $null
$Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri 
$Response.value |ft

我犯了同样的错误。

标签: powershellrestmicrosoft-graph-api

解决方案


我看到您正在使用应用程序机密,因此您使用的应用程序权限不受支持。需要委托。
查看请求的 Docs 页面,您可以在其中查看是否支持应用程序或委托。

在这里,您有两种获取委托访问令牌的方法: https ://gist.githubusercontent.com/leeford/04fc4c2d4404c2a31a172923d9bed8ee/raw/294f2303b306b4bf7a31f1541ff4d59dc5b40ca2/AzureADGraphAPIUserToken.ps1

https://www.lee-ford.co.uk/graph-api-device-code/


推荐阅读