在PowerShell中使用Microsoft Graph API获取计划程序任务

时间:2020-05-16 22:55:36

标签: powershell rest microsoft-graph-api

我正在尝试使用具有应用程序注册和权限的Microsoft Graph API来修改计划程序任务。 我已经成功注册了我的应用程序并将权限设置为(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

我遇到同样的错误。

1 个答案:

答案 0 :(得分:1)

我看到您正在使用应用程序密码,因此您正在使用不支持的应用程序权限。需要委派。
查看请求的“文档”页面,然后在此处查看是否支持应用程序或委托。

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

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