You need to enable JavaScript to run this app. PowerShell调用Azure DevOps Rest API分享Service Connection失败求解
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用Azure DevOps Rest API分享Service Connection失败求解

问题原因

这个错误是请求体结构不符合API要求导致的:
Azure DevOps共享服务连接的API要求传入的请求体是数组格式,哪怕你只需要共享给1个项目,也要将目标项目配置放在数组中。你当前直接传递了单个对象,服务端无法识别要求的endpointProjectReferences参数,因此抛出Value cannot be null. Parameter name: endpointProjectReferences的空参数错误。

另外你代码中还有两处冗余/潜在问题:

  • 存在无意义的$body = $body -replace "buildId", $pipelineID语句,你既没有定义$pipelineID变量,模板中也没有buildId占位符,属于冗余代码
  • 用字符串拼接构造JSON的方式容易出现转义、拼写错误,不如直接构造PowerShell对象更稳妥

解决方法

直接用PowerShell对象构造符合要求的请求体,修正后的函数代码如下:

function Share-ServiceConnection {
  param (
    $sc,
    $header,
    $project,
    $organisation, # 补充你之前未定义的organisation参数,避免变量作用域问题
    $targetProjectId, # 要共享到的目标项目ID,即你之前写死的af9444cb-e2b2-46fa-aa60-c471d9b309c6
    $targetProjectName # 要共享到的目标项目名称,即你之前写死的My Team
  )

  Write-Host "Share service connection: "$sc.Name 

  # 直接构造PowerShell对象,外层为数组符合API要求
  $body = @(
    @{
      projectReference = @{
        id = $targetProjectId
        name = $targetProjectName
      }
      name = "[$project] $($sc.Name)"
    }
  )

  # 转JSON时指定Depth参数避免层级过高被截断
  $bodyString = $body | ConvertTo-Json -Depth 10
  Write-Host "`nPATCH body request:"
  Write-Host $bodyString

  $URL ="https://dev.azure.com/$organisation/_apis/serviceendpoint/endpoints/$($sc.id)?api-version=6.0-preview.4" 
  Write-Host "`n PATCH URL:"
  write-host $URL

  try {
    Invoke-RestMethod -Method Patch -ContentType "application/json; charset=utf-8" -Uri $URL -Body $bodyString -Headers $header
  }
  catch {
    # 输出完整错误响应内容,方便后续排查问题
    $errorResponse = $_.Exception.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Error response: $responseBody"
    $_.Exception | Format-List -Force
  }
}

修正后调用函数传入对应参数即可正常完成共享操作。

内容的提问来源于stack exchange,提问作者BlueBunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 15:06:01