Evaluating Azure Devops Expressions within Powershell

Viewed 49

I want to be able to invoke the Counter expression within a template but I am unsure how to do so; my current template yml file looks like this:

parameters:
- name: major 
  type: string
  default: '1'
- name: minor 
  type: string
  default: '0'

steps: 

- task: PowerShell@2
  displayName: Set NuGet package version
  inputs:
    targetType: 'inline'
    script: |
      $isMain = ('$(Build.SourceBranch)' -eq 'refs/heads/main')

      $minor = ${{ parameters.minor }}
      $revision1 = $[counter($minor, 1)] 
      Write-Host $revision
      exit 0

But I get:

The term '$[counter' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I am guessing there is way I can invoke the function via Powershell.

The reason for me wanting to do this in the template as opposed to passing it in as a parameter from the consumer of the template is because seemingly parameters are not evaluated when passed into a template.

1 Answers

Evaluating Azure Devops Expressions within Powershell

Just as Daniel said that:

The powershell script you're trying to run is getting finalized during compile time. This line: $revision1 = $[counter($minor, 1)] cannot possibly work. You are trying to take the results of a powershell script expression and use it in a YAML function.

That is reason why it is not work for you.

And personally think you can go the easier way, just define the variable in the main YAML file:

azure-pipelines.yml:

variables:
  - name: minor
    value: 0
  - name: revision1
    value: $[counter(variables['minor'], 0)]


stages:
- stage: Run
  jobs:
  - job:
    steps:
      - template: Template.yml

And we could use the the Counter in the template directly:

Template.yml:

steps: 
- task: PowerShell@2
  displayName: Set NuGet package version
  inputs:
    targetType: 'inline'
    script: |
      Write-Host '$(revision1)'

The test result:

enter image description here

Related