尝试使用Powershell在VSTS中创建工作项时出现Bad Request错误

时间:2019-01-08 21:08:21

标签: powershell azure-devops azure-devops-rest-api

我尝试了多种方法来解决此错误,我从我的VSTS帐户创建了PAT,并将其包含在脚本中。但是,对REST API的调用返回说“远程服务器返回错误:(400)错误的请求”。

使用相同的PAT可以使用GET方法从VSTS中获取信息,但它不会创建工作项。

我正在按照以下步骤提供身份验证

$Creds = [Text.Encoding]::ASCII.GetBytes(":$Token")
$Creds = [System.Convert]::ToBase64String($Creds)
$Headers = @{
    Authorization = ("Basic {0}" -f $Creds)
}

并按照以下步骤传递其余内容

Invoke-RestMethod -Uri $Uri -Method POST -Headers $Headers -Body $Body -ContentType $ContentType

正文从CSV获取其值并存储在$ values

foreach ($value in $values)
{
   $PBIName = $value.Name
   $Resource = $value.Resource
   $Body        = "[
            {
                `"op`": `"add`",
    `"path`": `"/fields/System.Title`",
    `"value`": `"$($PBIName)`"
            }
            {
                `"op`": `"add`",
    `"path`": `"/fields/System.AreaPath`",
    `"value`": `"InfraEng\DCO`"
            }
            {
          `"op`": `"add`",
    `"path`": `"/fields/System.IterationPath`",
    `"value`": `"InfraEng`"
            }
            {
                     `"op`": `"add`",
    `"path`": `"/fields/System.AssignedTo`",
    `"value`": `"$($Resource)`"
            }]"

| ConvertTo-Json

并且URI如下

$ Uri =“ https://[xxxx].visualstudio.com/InfraEng/_apis/wit/workitems/`$ product backlog item?api-version = 1.0”

当我尝试触发Invoke-RestMethod时捕获响应时,得到以下信息

已通过身份验证:错误 Cookies:{VstsSession =%7B%22PersistentSessionId%22%3A%2248171d3c-4c0f-413f-9143-59e6e50047c3%22%2C%22PendingAuthenticationSessionId%22%3A%22                           00000000-0000-0000-0000-000000000000%22%2C%22CurrentAuthenticationSessionId%22%3A%2200000000-0000-0000-0000-0000-000000000000%22%7D} 标头:{Pragma,X-TFS-ProcessId,Strict-Transport-Security,ActivityId ...} 支持头:真 长度:373 ContentEncoding: ContentType:application / json;字符集= utf-8 字符集:utf-8 服务器: LastModified:1/9/2019 9:35:03 AM StatusCode:BadRequest 状态描述:错误的请求 协议版本:1.1 ResponseUri:https://[xxxx].visualstudio.com/InfraEng/_apis/wit/workitems/ $ product backlog item?api-version = 1.0 方法:开机自检 IsFromCache:错误

2 个答案:

答案 0 :(得分:0)

我不一定认为您的授权存在问题。我希望您可能会收到其他错误,特别是如果您能够在GET上使用标头。

这对我有用:

$Cred = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$pat"))
$Headers = @{
    Authorization = ("Basic {0}" -f $Cred)
}

Invoke-RestMethod -Uri 'https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/$Test Case?api-version=4.1' -Method PATCH -Header $Headers -Body '[{"op": "add","path": "/fields/System.Title","from": null,"value": "Sample test case"}]' -ContentType 'application/json-patch+json'

答案 1 :(得分:-1)

我认为您的问题与$Body有关,但未包含在问题中。

查看此页面-https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/create?view=azure-devops-rest-5.0