Home > Mobile >  How to write a foreach loop on build variable in Azure devops Powershell@2 task?
How to write a foreach loop on build variable in Azure devops Powershell@2 task?

Time:12-14

I have an azure pipeline that maintain a variable that holds project names - lets assume parameters.projects that holds projectA, projectB, projectC

I wish to execute a foreach loop and perform an operation on every project.

I currently use

- ${{ each Project in parameters.projects}}:
   - task: PowerShell@2
     displayName: "operation on [${{ Project }}]."
     inputs:
       targetType: 'inline'
       workingDirectory: $(System.DefaultWorkingDirectory)
       script: |
            New-Item -Path '$(Build.ArtifactStagingDirectory)\${{ Project }}' -ItemType Directory
            ....

In the above example the foreach argument (iteration value) is azure's, which means it will spwan a task for each project in the pipeline. This works but roughly slow.

I wish to run something like...

- task: PowerShell@2
  displayName: "operation on [${{ Project }}]."
  inputs:
    targetType: 'inline'
    workingDirectory: $(System.DefaultWorkingDirectory)
    script: |
        foreach ($Project in ${{ parameters.projects }}) 
        {
            New-Item -Path '$(Build.ArtifactStagingDirectory)\${{ Project }}' -ItemType Directory
            ....
        }

But i'm not sure about the syntax, and couldn't find a useful explanation/examples.

what is the right syntax? also a description web page it useful also.

CodePudding user response:

Runtime parameters let you have more control over what values can be passed to a pipeline. With runtime parameters you can:

Supply different values to scripts and tasks at runtime Control parameter types, ranges allowed, and defaults Dynamically select jobs and stages with template expressions

So, your current script is the right syntax.

I tested the object type parameters; It cannot be used in the PowerShell task.

You can try to use the string type parameters and split the string for loop.

YAML like:

parameters:
 - name: projects
   type: string
   default: project1;project2

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      # Write your PowerShell commands here.
      $prjs = "${{parameters.projects}}"
      $projects = $prjs -Split ";"
      foreach($project in $projects){
          New-Item -Path '$(Build.ArtifactStagingDirectory)\$project' -ItemType Directory
        }

For more information, you could refer to the runtime parameters.

  • Related