简体   繁体   中英

Azure DevOps Rest API Powershell call to share service connection fails

I'm working on a PowerShell script to share a Service Connection from one project with another. https://docs.microsoft.com/en-us/rest/api/azure/devops/serviceendpoint/endpoints/share%20service%20endpoint?view=azure-devops-rest-6.0

I GET the service connection in the root project and I pass it to the function to share it


function Share-ServiceConnection {
  param (
    $sc,
    $header,
    $project
  )

  Write-Host "Share service connection: "$sc.Name 
  
  
$body = "{
  `"projectReference`":
    {
      `"id`": `"af9444cb-e2b2-46fa-aa60-c471d9b309c6`",
      `"name`": `"My Team`"
    },
  `"name`": `"[projectName] scName`" 
}"

  $body = $body -replace "buildId", $pipelineID
  $body = $body -replace "projectName", $project
  $body = $body -replace "scName", $sc.Name
  
  $bodyJson=$body | ConvertFrom-Json
  Write-Host "`nPATCH body request:"
  $bodyString=$bodyJson | ConvertTo-Json
  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 {
    $_.Exception | Format-List -Force
  }

}

I know that the body content and the URL are correct, because it works in PostMan, but in PowerShell I get


Response       : StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
                 {
                   Cache-Control: no-store, must-revalidate, no-cache
                   Pragma: no-cache
                   P3P: CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOC CNT"
                   Set-Cookie: VstsSession=%7B%22PersistentSessionId%22%3A%2231f4d665-82fb-4b55-8800-77b3aad96ce6%22%2C%22PendingAuthenticationSessionId%22%3A%2200000000-0000-0000-0000-000000000000%22%2C%22CurrentAuthenticationSessionId%22%3A%2200000000-0000-0000-0000-000000000000%22%2C%22SignInState%22%3A%7B%7D%7D;SameSite=None; domain=.dev.azure.com; expires=Thu, 12-May-2022 08:30:18 GMT; path=/; secure; HttpOnly
                   X-TFS-ProcessId: 0afe2d8c-570c-4689-8070-e275d992d71e
                   Strict-Transport-Security: max-age=31536000; includeSubDomains
                   ActivityId: 28530af4-56d8-4856-a6fc-ed338a4cd92f
                   X-TFS-Session: 28530af4-56d8-4856-a6fc-ed338a4cd92f
                   X-VSS-E2EID: 28530af4-56d8-4856-a6fc-ed338a4cd92f
                   X-VSS-UserData: 7b2c35de-2845-6692-98e4-9b3366abe95a:Veselina@ascentsoftware.eu
                   X-Frame-Options: SAMEORIGIN
                   Request-Context: appId=cid-v1:a32646d4-6542-4ff0-b4b1-416ef6b2d466
                   Access-Control-Expose-Headers: Request-Context
                   X-Content-Type-Options: nosniff
                   X-Cache: CONFIG_NOCACHE
                   X-MSEdge-Ref: Ref A: E53666790D9D4E488BE1EBDABB2DA740 Ref B: MIL30EDGE1017 Ref C: 2021-05-12T08:30:18Z
                   Date: Wed, 12 May 2021 08:30:18 GMT
                   Content-Length: 224
                   Content-Type: application/json; charset=utf-8
                   Expires: -1
                 }
StatusCode     :
TargetSite     : Void ThrowTerminatingError(System.Management.Automation.ErrorRecord)
StackTrace     :    at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)
Message        : Response status code does not indicate success: 400 (Bad Request).
Data           : {}
InnerException :
HelpLink       :
Source         : System.Management.Automation
HResult        : -2146233088

The actual response I get is:

Invoke-RestMethod: {"$id":"1","innerException":null,"message":"Value cannot be null.\r\nParameter name: endpointProjectReferences","typeName":"System.ArgumentNullException, mscorlib","typeKey":"ArgumentNullException","errorCode":0,"eventId":0}

... and that confuses me a lot. I don't get what this parameter referring to.

I don't have any special characters in the body. The conversion from and back to a JSON is supposed to validate the structure... but something is still wrong and I don't see what.

Any suggestions?

The body after the ConverTo-Json:

{
  "projectReference": {
    "id": "af9444cb-e2b2-46fa-aa60-c471d9b309c6",
    "name": "My Team"
  },
  "name": "[RootProject] ServiceConnectionName"
}

According to my test, the request body should be like

[{
            "projectReference": {
                "id": "< the ID of the project you want to share the connection to>",
                "name": "<projectName>"
            },
            "name": "<connection name>"
}]

for example

$pat=""
$userName=""

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$pat)))

$header=@{
 "Content-Type"="application/json";
 "Authorization"=("Basic {0}" -f $base64AuthInfo)

}

$body=@( @{
            "projectReference"=@{
                "id"= "292920a******0060a7be7";
                "name"= "mytest"
            };
            "name"= "GitHub connection 1"
})

$bodyString= ConvertTo-Json $body


$URL="https://dev.azure.com/jim0375/test/_apis/serviceendpoint/endpoints/{id}?api-version=6.0-preview.4"

try {
    Invoke-RestMethod -Method Patch -ContentType "application/json; charset=utf-8" -Uri $URL -Body $bodyString -Headers $header
  }
  catch {
    $_.Exception | Format-List -Force
  }

在此处输入图像描述 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM