创建发布 JSON 主体在 Postman 中有效,但在 PowerShell 脚本中无效

Create Release JSON body works in Postman but not in PowerShell script

使用 Azure DevOps REST API 和 PowerShell,我正在尝试创建一个非常基本的发布管道。我的 JSON 主体在 Postman 中运行良好,但在 PowerShell 中使用 Invoke-RestMethod 运行 时出错。

我正在关注 https://docs.microsoft.com/en-us/rest/api/azure/devops/build/definitions/create?view=azure-devops-rest-5.0 中的文档。

使用 Postman,我创建了一个 JSON 主体,它可以完美且重复地工作(前提是我更改发布管道名称或删除之前创建的管道名称)。我已将 JSON 内容逐字复制到我的 PowerShell 脚本中,将变量 $requestBody 设置为等于 JSON 内容。当我 运行 脚本时,出现错误(错误内容见下文)。

以下是我的测试脚本(对长度表示歉意,但我认为包含整个 JSON.

很重要
$organization = "ORGNAME"
$token = "6-OBFUSCATED_TOKEN-a"
$project = "PROJECTNAME"

# Base64-encode the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $token)))

$uri = "https://dev.azure.com/$($organization)/$($project)/_apis/build/definitions?api-version=5.0"

$requestBody = '{
  "source": "restAPI",
  "revision": 1,
  "description": null,
  "name": "RepoName-CD",
  "path": "\",
  "projectReference": null,
  "properties": {},
  "environments": [
      {
          "name": "Stage 1",
          "variables": {},
          "variableGroups": [],
          "preDeployApprovals": {
              "approvals": [
                  {
                      "rank": 1,
                      "isAutomated": true,
                      "isNotificationOn": false
                  }
              ],
              "approvalOptions": {
                  "requiredApproverCount": null,
                  "releaseCreatorCanBeApprover": false,
                  "autoTriggeredAndPreviousEnvironmentApprovedCanBeSkipped": false,
                  "enforceIdentityRevalidation": false,
                  "timeoutInMinutes": 0,
                  "executionOrder": "beforeGates"
              }
          },
          "postDeployApprovals": {
              "approvals": [
                  {
                      "rank": 1,
                      "isAutomated": true,
                      "isNotificationOn": false
                  }
              ],
              "approvalOptions": {
                  "requiredApproverCount": null,
                  "releaseCreatorCanBeApprover": false,
                  "autoTriggeredAndPreviousEnvironmentApprovedCanBeSkipped": false,
                  "enforceIdentityRevalidation": false,
                  "timeoutInMinutes": 0,
                  "executionOrder": "afterSuccessfulGates"
              }
          },
          "deployPhases": [
              {
                  "deploymentInput": {
                      "parallelExecution": {
                          "parallelExecutionType": "none"
                      },
                      "skipArtifactsDownload": false,
                      "artifactsDownloadInput": {
                          "downloadInputs": []
                      },
                      "demands": [],
                      "enableAccessToken": false,
                      "timeoutInMinutes": 0,
                      "jobCancelTimeoutInMinutes": 1,
                      "condition": "succeeded()",
                      "overrideInputs": {}
                  },
                  "rank": 1,
                  "phaseType": "agentBasedDeployment",
                  "name": "Agent job",
                  "refName": null,
                  "workflowTasks": []
              }
          ],
          "environmentOptions": {
              "emailNotificationType": "OnlyOnFailure",
              "emailRecipients": "release.environment.owner;release.creator",
              "skipArtifactsDownload": false,
              "timeoutInMinutes": 0,
              "enableAccessToken": false,
              "publishDeploymentStatus": true,
              "badgeEnabled": false,
              "autoLinkWorkItems": false,
              "pullRequestDeploymentEnabled": false
          },
          "executionPolicy": {
              "concurrencyCount": 1,
              "queueDepthCount": 0
          },
          "schedules": [],
          "retentionPolicy": {
              "daysToKeep": 30,
              "releasesToKeep": 3,
              "retainBuild": true
          },
          "processParameters": {},
          "properties": {},
          "environmentTriggers": []
      }
  ]
}'

Invoke-RestMethod -Uri $uri -Method POST -ContentType "application/json" -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo) } -Body $requestBody

当我 运行 脚本时,我希望返回 JSON 确认发布管道已创建,但我从 PowerShell 收到以下错误。

Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Value cannot be null.\r\nParameter name: definition.Repository","typeName":"System.ArgumentNullException, mscorlib","typeKey":"ArgumentNullException","errorCode":0,"eventId":0} 在 C:\GitHub\landingzone\AzureDevOpsApiDev\testmule.ps1:113 char:1 + Invoke-RestMethod -Uri $uri -Method POST -ContentType “application/js ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation:(System.Net.HttpWebRequest:HttpWebRequest)[Invoke-RestMethod],WebException + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

如有任何帮助或指导,我们将不胜感激。

您似乎正在对创建构建定义 API 创建 POST。如果您尝试创建发布定义,您可能需要 post 到 URL 像这样

POST https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions?api-version=5.0

好吧,这里的教训是不要在没有仔细检查的情况下从以前工作的脚本中复制和粘贴代码。

我认错了。