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

Bad Request error while trying to create a work item in VSTS using Powershell

我已经尝试了很多方法来解决这个错误,我已经从我的 VSTS 帐户创建了一个 PAT,并将其包含在脚本中。但是,调用 REST API returns 说 "The remote server returned an error: (400) Bad Request".

使用相同的 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

Body 从 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/`$产品积压项?api-version=1.0"

当我尝试在触发 Invoke-RestMethod 时捕获响应时,我得到以下内容

IsMutuallyAuthenticated:假 饼干:{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-000000000000%22%7D} Headers : {Pragma, X-TFS-ProcessId, Strict-Transport-Security, ActivityId...} 支持Headers : 是 内容长度:373 内容编码: 内容类型:application/json;字符集=utf-8 字符集:utf-8 服务器 : LastModified : 1/9/2019 9:35:03 上午 状态代码:错误请求 状态描述:错误请求 协议版本:1.1 ResponseUri : https://[xxxx].visualstudio.com/InfraEng/_apis/wit/workitems/$产品积压项目?api-version=1.0 方法:POST IsFromCache:假

我认为您的问题与 $Body 有关,但这不包括在问题中。

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

我认为不一定是你授权的问题。我希望您可能会遇到不同的错误,尤其是如果您能够在 GET 上使用 header。

这对我有用:

$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'