azureazure-pipelinescicd

Azure pipeline get Pull request source and target branch name


I want to check whether particular file changed in azure pipeline between two branches of pull request (source & target) So I wanted the source and target branch name, its showing error.

Here is my script:

task: PowerShell@2
      displayName: 'Detect file changes'
      inputs: 
        targetType: 'inline'
        script: |
          $sourceBranch=$env:SYSTEM_PULLREQUEST_SOURCEBRANCH
          Write-Host "$sourceBranch" 

Tried with below scripts:

$sourceBranch=$env:SYSTEM_PULLREQUEST_SOURCEBRANCH --> returns empty $sourceBranch=$(System.PullRequest.SourceBranch) --> object not found $(System.PullRequest.SourceBranch)

any help:


Solution

  • Based on your comment, the Pipeline is triggered when PR is merged. In this case, the pipeline will be considered as CI trigger.

    To get the Pull Request related Pipeline variable, you can set the Pipeline in Branch Policy -> Build validation.

    For example:

    enter image description here

    When the Pull Request is created, it will trigger Pipeline and show the related variable(e.g. System.PullRequest.SourceBranch)

    Result:

    enter image description here

    enter image description here

    For more detailed info, you can refer to this doc: Predefined variables

    System.PullRequest.SourceBranch

    The branch that is being reviewed in a pull request. For example: refs/heads/users/raisa/new-feature for Azure Repos. (This variable is initialized only if the build ran because of a Git PR affected by a branch policy). This variable is only available in a YAML pipeline if the PR is affected by a branch policy.