0

my 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

My 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": ""
                        }
                    ]
                }
            ]
        }
    }
]

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

When I run the script with that Azure DevOps task with that json as input I get output:

shoessing count: 
shoessing count: 2

But when I run this script locally I get:

shoessing count: 1
shoessing count: 2

I made this fairly simple powershell to identify the problem I have with another script. It works fine in my local setup Windows 10 + Powershell. How I can make the powershell in Azure DevOps pipelines to identify single item json array correctly? The powershell in Azure DevOps task does not take depth as variable.

Kamsiinov
  • 1,315
  • 2
  • 20
  • 50

1 Answers1

1

I can only reproduce this behavior with ConvertFrom-Json in Windows PowerShell 5.1 - which I guess is what the Azure DevOps agent is running - wrap the resulting object in an array subexpression (@()) to get the actual Count:

    Write-Output "shoessing count: $(@($shoessing).Count)"
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206