Home > database >  Azure devops pipeline, powershell split string, convert to json and assign to pipeline variable does
Azure devops pipeline, powershell split string, convert to json and assign to pipeline variable does

Time:03-19

I want to convert a pipeline variable - delimited string - to a json array and assign the json array to an other pipeline variable. See my code below, output stays empty. What am I missing here?

script:

steps:
  - task: PowerShell@2
    inputs:
      targetType: inline
      script: |
        $test = "LZ-UK;LZ-ES;LZ-NL"
        $json = $test.Split(";") | ConvertTo-Json -AsArray
        Write-Host "##vso[task.setvariable variable=JsonLZ]$json"
        Write-Host "Assigned the variable"
        Write-Host "New `r`n $($JsonLZ)"
  - script: |
       echo ${{ variables.JsonLZ }}

output:

Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Linux, macOS, or Windows
Version      : 2.200.0
Author       : Microsoft Corporation
Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
==============================================================================
Generating script.
========================== Starting Command Output ===========================
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command . '/home/vsts/work/_temp/380b437f-74c4-4883-9d4a-7b4f3ac79266.ps1'
  "LZ-UK",
  "LZ-ES",
  "LZ-NL"
]
Assigned the variable
New 
 
Finishing: PowerShell

CodePudding user response:

You're very close. There were a few minor issues that I spotted with your YAML/PowerShell:

  1. You forgot the semicolon after the variable name in "##vso[task.setvariable variable=JsonLZ]$json", it should be: "##vso[task.setvariable variable=JsonLZ;]$json"
  2. You should be using $(JsonLZ) instead of ${{ variables.JsonLZ }}. The former will be evaluated at runtime, the latter at compile-time. Here's a link to the MS Docs: Understand variable syntax

Give this a try to see a working example:

name: Stackoverflow-Example-Pipeline
trigger:
    - none
variables:
  JsonLZ: 'UNSET'
stages:
    - stage: StageA
      displayName: "Stage A"
      jobs:
        - job: example_job
          displayName: "Example Job"
          pool:
            vmImage: "ubuntu-latest"
          steps:
          - task: PowerShell@2
            inputs:
              targetType: inline
              script: |
                  $test = "LZ-UK;LZ-ES;LZ-NL"
                  $json = $test.Split(";") | ConvertTo-Json -Compress
                  Write-Host "##vso[task.setvariable variable=JsonLZ;]$json"
                  Write-Host "Assigned the variable"
          - script: |
              echo $(JsonLZ)
              echo ${{ variables.JsonLZ }}
  • Related