Bastiaan
Bastiaan

Reputation: 736

Use Json variable between two PowerShell steps

In an Azure Devops Pipeline I need to pass over a Json variable from a Powershell script in step 1 to another Powershell script in step 2. The double quotes of the Json variable seem to be messing things up. Escaping them also does not seem to work.

Here the 2 steps:

- task: PowerShell@2
  displayName: 'Debug -> Step 1'
  inputs:
    targetType: 'inline'
    script: |      
      $json = [pscustomobject]@{ prop1 = "value1"; prop2 = "value2" } | ConvertTo-Json
      Write-Host "##vso[task.setvariable variable=MYVAR]$json"

- task: PowerShell@2
  displayName: 'Debug -> Step 2'
  inputs:
    targetType: 'inline'
    script: |
      echo $env:MYVAR

This results in:

enter image description here

Any idea how I can pass an object (in Json) to another step?

Upvotes: 0

Views: 550

Answers (1)

Levi Lu-MSFT
Levi Lu-MSFT

Reputation: 30373

The logging command ##vso[task.setvariable] can only accept a single line string. You need to use -Compress to convert the json object to a single line string. See below example:

$json = [pscustomobject]@{ prop1 = "value1"; prop2 = "value2" } | ConvertTo-Json -Compress
Write-Host "##vso[task.setvariable variable=MYVAR]$json "

Upvotes: 3

Related Questions