Microsoft Graph PowerShell邮件移动POST请求报400错误求助
解决Microsoft Graph API移动邮件时的400错误
你的问题出在两个关键细节上:
- JSON字段大小写不匹配:Graph API要求请求体字段为
destinationId(驼峰命名,首字母小写),但你代码里写的是destinationID(末尾D大写),API无法识别该字段导致400错误。 - 请求体格式错误:直接传入哈希表给
-Body参数时,Invoke-RestMethod默认会用application/x-www-form-urlencoded格式发送数据,而Graph API需要JSON格式,必须先将哈希表转换为JSON字符串。
修正后的函数代码如下:
# This function moves an email object to a given folder in Outlook in o365 function moveEmail { param( $Credential, [string] $UserPrincipalName, [string] $folderId, [string] $folderDestinationId, [string] $emailId) $Header = Get-Header -theRequest $Credential $restUrl = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/mailFolders/$folderId/messages/$emailId/move" # 修正字段名并转换为JSON格式 $Body = @{ destinationId = $folderDestinationId } | ConvertTo-Json try { $emailResult = Invoke-RestMethod -Method Post -Uri $restUrl -Headers $Header -Body $Body -ContentType "application/json" -ErrorAction Stop return $emailResult } catch { # 输出详细错误信息辅助调试 Write-Error "请求失败: $_" # 读取API返回的具体错误描述 if ($_.Exception.Response) { $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) $responseBody = $reader.ReadToEnd() Write-Error "API响应详情: $responseBody" } } }
额外调试提示:如果仍报错,通过catch块的代码可以获取API返回的具体错误内容,里面会明确指出问题根源(比如权限不足、文件夹ID无效等)。
内容的提问来源于stack exchange,提问作者robert_longworth
相关产品推荐
相关产品推荐

