Is there is a way to get Pull Request ID in Azure DevOps after clicking on complete button in Pull Request

Viewed 3221

I'm executing a pipeline flow after creating a PR and I need to get Pull Request ID after I click the complete button.

I'm using $(System.PullRequest.PullRequestId) to fetch the value, but it is always an empty value and gives the error output "System.PullRequest.PullRequestId: command not found"

Create a simple classical pipeline like below and it needs to be called in Branch Policies -> Status Check. enter image description here

Note: With the same variable $(System.PullRequest.PullRequestId) I'm able to get the ID before the completion i.e., when PR is in an active state.

1 Answers

Ad @CodeCaster said in the comment, the variable $(System.PullRequest.PullRequestId) is initialized only if the build ran because of a Git PR affected by a branch policy.

But, you can get the last completed PR ID with small PS script via the Rest API:

$header = @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"  }
$url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.Name)/pullrequests/?searchCriteria.status=3&top=50&searchCriteria.targetRefName=refs/heads/master&api-version=6.1"
$pullRequests = Invoke-RestMethod -Uri $url -Method Get -Headers $header -ContentType application/json
Write-Host "Last PR completed to master is: $($pullRequests.value[0].pullRequestId)"

Just replace the master in the $url with your target branch name.

Results: enter image description here

Don't forget to enable the access token if you use the Classic editor or add the token to your YAML task.

Related