使用 PowerShell 在 Azure DevOps 中更新服务挂钩

Update Service Hook in Azure DevOps Using PowerShell

想知道是否有人知道如何执行此操作,因为我一直在努力这样做。

我正在尝试编写一个 PowerShell 脚本,希望它能更新我们在 Azure DevOps 中设置的任何服务挂钩,使它们的状态变为启用状态。偶尔ADO会禁用它们,我认为是由于长时间不活动,这是一种痛苦。

到目前为止,我有以下内容,但我收到一条错误消息

"The notification subscription "2092cfc4-a95b-4800-976e-67ccf9deb4b1" for service hook subscription "2e0a69e7-c4aa-44ad-89d7-ca1e3809585e" no longer exists."

我明白了,但不确定如何解决。 我确定它存在,因为如果我使用 $uri2,用循环中的 $item 变量之一填充 subscriptionId,然后放入浏览器,我得到像这样返回的 json,所以它找到它是对的吗?

我一直在参考此页面上的各种文档: https://docs.microsoft.com/en-us/rest/api/azure/devops/hooks/subscriptions/replace%20subscription?view=azure-devops-rest-5.1

我认为我首先需要获取所有 Web 挂钩订阅的列表,然后遍历每个获取 Id 的列表,在另一个请求中使用该 Id 来更新服务挂钩。我怀疑一半的问题与我对它是如何完成的理解有关,如果可能的话,我想我会在这里问。

有没有人完成过这个或者可能有一些关于如何更新字段的示例脚本?不确定我是否需要将更多数据传递到正文中。

cls

$User = 'myUser'
$PersonalAccessToken = 'myPatToken'
$base64authinfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f  $User, $PersonalAccessToken)))
$vstsAccount = "myOrgName"

$uri1 = "https://dev.azure.com/$vstsAccount/_apis/hooks/subscriptions?api-version=5.1"

$hooks = Invoke-RestMethod -Method Get -ContentType application/json -Uri $uri1 -Headers @{Authorization=("Basic {0}" -f $base64authinfo)}

foreach ($item in $hooks.value) {

    $body = @{
        "publisherId" = "tfs"
        "eventType" = "$($item.eventType)"
        "resourceVersion" = "1.0"
        "consumerId" = "webHooks"
        "consumerActionId" = "httpRequest"
        "status" = "enabled"
    }

    $bodyJson = $body | ConvertTo-Json

    write-host "current status: $($item.status)"
    write-host "$($item.id)"
    write-host "$($item.eventType)"

    $uri2 = "https://dev.azure.com/$vstsAccount/_apis/hooks/subscriptions/$($item.id)?api-version=5.1"
    write-host $uri2
    Invoke-RestMethod -Method Put -ContentType application/json -Uri $uri2 -Headers @{Authorization=("Basic {0}" -f $base64authinfo)} -Body $bodyJson
    
}

Update Service Hook in Azure DevOps Using PowerShell

我可以用你的请求正文重现这个问题。

那是因为我们在请求正文中丢失了一些基本参数:

从上图可以看出,如果我把projectId这个参数注释掉,就会出现和你一样的错误

根据REST API Subscriptions - Replace Subscription的示例,我们可以得到请求体:

{
  "publisherId": "tfs",
  "eventType": "build.complete",
  "resourceVersion": "1.0-preview.1",
  "consumerId": "webHooks",
  "consumerActionId": "httpRequest",
  "publisherInputs": {
    "buildStatus": "Failed",
    "definitionName": "MyWebSite CI",
    "projectId": "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c"
  },
  "consumerInputs": {
    "url": "https://myservice/myhookeventreceiver"
  }
}

因此,我们可以使用此请求正文来调用 REST API。

注:

  • 在您的请求正文中使用 : 而不是 =
  • 在请求正文中替换与您的订阅匹配的值,并根据您的需要添加其他参数。

另外,我看到你用foreach更新了所有订阅,但是需要特别注意并非所有订阅的 publisherIdconsumerIdconsumerActionId 都是相同的。批量修改时要特别注意。

测试结果:

希望对您有所帮助。