【问题标题】:Azure DevOps powershell task convertfrom-json command misses one item arrays [duplicate]Azure DevOps powershell 任务 convertfrom-json 命令缺少一项数组 [重复]
【发布时间】:2020-12-27 04:19:00
【问题描述】:

我的 runscript.yml:

parameters:
  agentPool: ''
  agentImage: ''
    
jobs:
- job: runscript
  displayName: runscript
  pool:
    name: '${{ parameters.agentPool }}'
    vmImage: '${{ parameters.agentImage }}'

  steps:
  - task: AzurePowerShell@4
    displayName: 'Azure PowerShell'
    inputs:
      azureSubscription: 'dops'
      ScriptPath: 'scripts/Test-JSON'
      ScriptArguments: '-jsonPath "$(System.DefaultWorkingDirectory)/json/test.json"'
      azurePowerShellVersion: LatestVersion

我的 test.json:

[
    {
        "DisplayName": "Best from best",
        "gnm": {
            "shoessing": [
                {
                    "mime": [
                        {
                            "id": "262364362673",
                            "key": ""
                        }
                    ]
                }
            ]
        }
    }
    {
        "DisplayName": "Trying to be best",
        "gnm": {
            "shoessing": [
                {
                    "mime": [
                        {
                            "id": "262364362673",
                            "key": ""
                        },
                        {
                            "id": "AAAAAAAAA",
                            "key": ""
                        }
                    ]
                }
            ]
        }
    }
]

测试-JSON.ps1:

param (
    [string]$jsonPath
)
function Test-JSON {
    param (
        [string]$File
    )
    $long = "mime"
    $json = Get-Content $file | ConvertFrom-Json
    for ($i = 0; $i -lt $json.Count; $i++) {
        foreach ($gnm in $json[$i].gnm) {
            $shoessing = $gnm.shoessing.$long
            Write-Output "shoessing count: $($shoessing.Count)"
        }
    }
}
Test-JSON -File $jsonPath

当我使用该 json 作为输入的 Azure DevOps 任务运行脚本时,我得到输出:

shoessing count: 
shoessing count: 2

但是当我在本地运行这个脚本时,我得到:

shoessing count: 1
shoessing count: 2

我制作了这个相当简单的 powershell 来识别我在另一个脚本中遇到的问题。它在我的本地设置 Windows 10 + Powershell 中运行良好。如何使 Azure DevOps 管道中的 powershell 正确识别单个项目 json 数组? Azure DevOps 任务中的 powershell 不将深度作为变量。

【问题讨论】:

  • 您在两个顶级数组元素之间缺少,

标签: json azure powershell azure-devops


【解决方案1】:

我只能在 Windows PowerShell 5.1 中使用 ConvertFrom-Json 重现此行为 - 我猜这是 Azure DevOps 代理正在运行的 - 将结果对象包装在数组子表达式 (@()) 中以获得实际的 Count

    Write-Output "shoessing count: $(@($shoessing).Count)"

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多