PowerShell模拟Postman调用Graph API设置SharePoint站点权限报错
错误点
- 调用POST接口时传入了未序列化的PowerShell哈希表对象作为请求体:你已经提前将请求体序列化为JSON字符串存储在
$bodyTxt变量中,但实际调用Invoke-WebRequest时传入的是原始哈希表$body,Graph API仅接收JSON格式的请求体,所以返回Bad Request错误。 - 请求头中的Content-Type字段配置不规范:你在Headers表中定义的键名为
ContentType,正确的HTTP头字段名应为Content-Type,也可以直接通过Invoke-WebRequest的-ContentType参数指定,避免拼写错误。
修正后的代码段
cls # https://learn.microsoft.com/en-us/graph/api/site-get-permission?view=graph-rest-1.0&tabs=http $secret = "xxx.5i2v" $clientid="xx-45f3-464f-xx-xx" $tenantid="xx-x-4f1f-xx-x" $Body = @{ 'tenant' = $tenantid 'client_id' = $clientid 'scope' = 'https://graph.microsoft.com/.default' 'client_secret' = $secret 'grant_type' = 'client_credentials' } $Params = @{ 'Uri' = "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" 'Method' = 'Post' 'Body' = $Body 'ContentType' = 'application/x-www-form-urlencoded' } $AuthResponse = Invoke-RestMethod @Params $Headers = @{ 'Authorization' = "Bearer $($AuthResponse.access_token)" } # 权限查询请求保持不变 $Result = Invoke-RestMethod -Uri 'https://graph.microsoft.com/v1.0/sites/xx-53D2-xx-xx-xx/permissions' -Headers $Headers $bodyTxt = $Result | ConvertTo-Json -Depth 100 write-host $bodyTxt $body = @{ roles = @("write") grantedToIdentities = @( @{ application = @{ displayName = "Test 7" id = "xx-45f3-xx-aac4-xx" } }) } $bodyTxt = $body | ConvertTo-Json -Depth 100 # 修正后的POST请求:传入序列化后的JSON字符串,显式指定Content-Type Invoke-WebRequest -Uri 'https://graph.microsoft.com/v1.0/sites/xx-53D2-xx-xx-xx/permissions' -Method POST -Body $bodyTxt -Headers $Headers -ContentType 'application/json'
内容的提问来源于stack exchange,提问作者Thomas Segato
相关产品推荐
相关产品推荐

