powershellazure-devopsazure-pipelines

Unable to update variables in powershell script of azure devops yml file


I have gone through Microsoft official document and tried exactly what is defined there. Tried both Write-Host & echo but still unable to update the variables.

Here is the link: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/set-variables-scripts?view=azure-devops&tabs=powershell

But unable to achieve this.

variables:
- name: majorVersion
  value: "0"
- name: minorVersion
  value: "0"
- name: patchVersion
  value: "0"
- name: counterNumber
  value: "0"
- name: update
  value: false


jobs:
- job: Build
  pool:
    vmImage: 'windows-latest'
  steps:
  - powershell: |
          
          echo "##vso[task.setvariable variable=update]true"
          Write-Host "##vso[task.setvariable variable=majorVersion;]$versionParts[0]"
          Write-Host "##vso[task.setvariable variable=minorVersion;]$versionParts[1]"
          Write-Host "##vso[task.setvariable variable=patchVersion;]$patch"
        

Solution

  • Refer to this doc: Set variables in scripts

    A script in your pipeline can define a variable so that it can be consumed by one of the subsequent steps in the pipeline.

    When you use command to update the Pipeline variables, it will not work on the current task, but the values can be used in the next tasks.

    Here is an example to update the variables and use it in next tasks:

    variables:
    - name: majorVersion
      value: "0"
    - name: minorVersion
      value: "0"
    - name: patchVersion
      value: "0"
    - name: counterNumber
      value: "0"
    - name: update
      value: false
    
    
    jobs:
    - job: Build
      pool:
        vmImage: 'windows-latest'
      steps:
      - powershell: |
              $versionParts = @(1,2)
              $patch = 3
              $major = $versionParts[0]
              $minor = $versionParts[1]
              echo "##vso[task.setvariable variable=update]true"
              echo "##vso[task.setvariable variable=majorVersion;]$major"
              echo "##vso[task.setvariable variable=minorVersion;]$minor"
              echo "##vso[task.setvariable variable=patchVersion;]$patch"
        displayName:  Update Variable 
      - powershell: |
              echo $(update)
              echo $(majorVersion)
              echo $(minorVersion)
              echo $(patchVersion)
        displayName:  Use Variable 
    

    Result:

    enter image description here