Azure devops 管道、powershell 拆分字符串、转换为 json 并分配给管道变量不起作用

Azure devops pipeline, powershell split string, convert to json and assign to pipeline variable doesn't work

我想将管道变量(分隔字符串)转换为 json 数组并将 json 数组分配给另一个管道变量。请参阅下面的代码,输出保持为空。我在这里错过了什么?

脚本:

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 }}

输出:

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

你非常接近。我发现您的 YAML/PowerShell:

存在一些小问题
  1. 你忘了"##vso[task.setvariable variable=JsonLZ]$json"中变量名后面的分号,应该是:"##vso[task.setvariable variable=JsonLZ;]$json"
  2. 您应该使用 $(JsonLZ) 而不是 ${{ variables.JsonLZ }}。前者将在 runtime 时评估,后者在 compile-time 时评估。这是 MS 文档的 link:Understand variable syntax

试一试以查看工作示例:

name: Whosebug-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 }}