无法使用Invoke-RestMethod

时间:2020-06-07 15:46:21

标签: powershell azure-devops tfs-workitem

我正在尝试从PowerShell向工作项历史记录中添加一些信息。

发送例如json

[
{
    "path":  "/fields/System.History",
    "op":  "add",
    "value":  "Created by:\r\nRené Spišák\r\n\r\nTitle:\r\nPull request\r\n\r\nDescription:\r\nTest description"
}
]

链接

https://XXX.visualstudio.com/XXX/_apis/wit/workitems/14611?api-version=5.1

使用

Invoke-RestMethod $workItemUrl -ContentType "application/json-patch+json" -Method "PATCH" -Headers $headers -Body $jsonBody

以错误结束

Invoke-RestMethod : {"$id":"1","innerException":null,"message":"You must pass a valid patch document in the body of 
the request.","typeName":"Microsoft.VisualStudio.Services.Common.VssPropertyValidationException, 
Microsoft.VisualStudio.Services.Common","typeKey":"VssPropertyValidationException","errorCode":0,"eventId":3000}
At C:\agent\_work\_temp\afb9aee6-21d2-4ea1-b455-916baee6d74b.ps1:127 char:29
+ ... mResponse = Invoke-RestMethod $workItemUrl -ContentType "application/ ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc 
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

使用Postman将相同的json发送到相同的url效果很好。

此api有什么问题?什么是“有效补丁文件”?

如何将格式化的(换行符,html等)文本发送到工作项api?
https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1

编辑:
只是为了澄清-问题仅在json的value字段中。脚本的其他部分工作正常。我可以使用Postman将此JSON发布到WIT Api。所有作品。但是使用Invoke-RestMethod失败。

那么,也许PowerShell以不同的方式处理发送Json吗?转义?字符集?

已解决:
错误的ContentType,必须为“ application / json-patch + json; charset = utf-8”

1 个答案:

答案 0 :(得分:1)

似乎powershell无法识别“RenéSpišák”字符,请尝试其他字符。