【发布时间】:2021-03-17 16:22:06
【问题描述】:
我一直在编写一个 powershell 脚本来使用 Graph API 来设置邮箱规则。基本上我遵循了这个guide 我可以按照指南创建文件夹,但是当我尝试编辑脚本并用这个info 替换正文以创建消息规则时它失败了。我正在努力找出原因。有人知道我可能会出错的地方吗?
## Details for mailboxes and folders needed. Obviously you can get these as parameters if need be.
For AdHoc code I use "Get-Clipboard" quite often. Here a fixed array as something to start with.
$Mailboxes = @("mailbox")
## Before next step aquire access token, if you need help this blog has a great example https://adamtheautomator.com/microsoft-graph-api-powershell/. For simplicity, I have used here an application secret.
# Define AppId, secret and scope, your tenant name and endpoint URL
$AppId = "ID"
$AppSecret = "Secret"
$Scope = "https://graph.microsoft.com/.default"
$TenantName = "name"
$Url = "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token"
# Add System.Web for urlencode
Add-Type -AssemblyName System.Web
# Create body
$Body = @{
client_id = $AppId
client_secret = $AppSecret
scope = $Scope
grant_type = 'client_credentials'
}
# Splat the parameters for Invoke-Restmethod for cleaner code
$PostSplat = @{
ContentType = 'application/x-www-form-urlencoded'
Method = 'POST'
# Create string by joining bodylist with '&'
Body = $Body
Uri = $Url
}
# Request the token!
$Request = Invoke-RestMethod @PostSplat
# Create header
$Header = @{
Authorization = "$($Request.token_type) $($Request.access_token)"
}
## Thanks, now we have token ready for use. Lets use GRAPH's mailFolders API
## Loop through mailbxoes
foreach($mailbox in $Mailboxes) {
$Uri = "https://graph.microsoft.com/v1.0/users/$mailbox/mailFolders/inbox/messageRules"
$Body = @"
{
"displayName": "Test",
"sequence": 2,
"isEnabled": true,
"conditions": {
"importance": [
"low"
]
},
"actions": {
"copyToFolder": [
"Low Priority"
],
"stopProcessingRules": true
}
}
"@
$NewRule = Invoke-RestMethod -Uri $Uri -Headers $Header -Method Post -Body $Body -ContentType "application/json"
}
【问题讨论】:
-
您收到的错误信息是什么?
-
我得到的错误是:Invoke-RestMethod:远程服务器返回错误:(400)错误请求。在 C:\Ry Files\Powershell\mailrule.ps1:67 char:15 + ... $NewRule = Invoke-RestMethod -Uri $Uri -Headers $Header -Method Post ... + ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
标签: powershell microsoft-graph-api