azure-devopsazure-pipelines

Run Azure DevOps Pipeline with Particular Branch using API


Here is the PowerShell script I am running:

$apiUrl = "$organizationUrl/$project/_apis/pipelines/$definitionId/runs?api-version=7.1"

$requestBody = @{
    resources = @{
        repositories = @{
            self = @{
                refName = "refs/heads/targetBranch"
            }
        }
    }
    runResources = @{
        parameters = @{
            myVariable          = "myValue"
            myOtherVariable     = "someValue"
        }
    }
} | ConvertTo-Json

$headers = @{
    "Authorization" = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$pat"))
    "Content-Type" = "application/json"
}

Invoke-RestMethod -Method Post -Uri $apiUrl -Headers $headers -Body $requestBody

This successfully queues the pipeline run, but it checks out "main" instead of "targetBranch".

How do I make it use the branch that I want?


Solution

  • The problem was the depth in converting to JSON. The default is too shallow, so "self" was coming out as an object reference, not the string. Just need to add the -Depth flag with enough to get down to it.

    | ConvertTo-Json -Depth 20