powershellazure-pipelinesazure-devops-server

Use timestamp variable in azure devops pipeline


I am stuck at using build variables in azure devops pipelines.

What I try to achieve: Create variable with the current timestamp and use this variable to set the build name and the artifact version (for traceability).

In my current configuration the powershell script is executed successfully but the variable foo is empty in the npm step (see yml code below).

variables:
  system.debug: true

name: $(TeamProject)_$(Build.DefinitionName)_$(SourceBranchName)_$(Date:yyyyMMdd)-$(Hours)$(Minutes)$(Seconds)

[...]

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Write-Host "Setting up the date time for build variable"
      $date=$(Get-Date -format yyyyMMdd-Hmmss)
      Write-Host "##vso[task.setvariable variable=foo]$date"'

- task: Npm@1
  inputs:
    command: 'custom'
    customCommand: '--no-git-tag-version version prerelease --preid=dev-$(foo)'
  displayName: 'npm version prerelease'

My questions: Why is the variable foo (introduced with powershell) empty in the npm step? Is there a way to set the build name with the self introduced variable foo (to use the same timestamp for build name and artifact version)?


Solution

  • You are using the wrong format of your YAML pipeline. You could use below snippet:

    steps:
    - powershell: |
       Write-Host "Setting up the date time for build variable"
       $date=$(Get-Date -format yyyyMMdd-Hmmss)
       Write-Host "##vso[task.setvariable variable=foo]$date"
      displayName: 'PowerShell Script'
    

    Then this foo variable should introduced with powershell succeed. You will see it expand in follow npm task.

    enter image description here