How can i convert Payload with array of JSON objects in PowerShell?

  Kiến thức lập trình

I am currently facing issue where in I cant able to convert the payload into array of Json objects
[{}] in powershell. I am using below code and I am getting only JSON object in output which is not expected

$testResultsPath = "path to XML file"
$testRunId = $env:runID
$organization = "XXXXX"
$project = "$(System.TeamProject)"
$pat = "XXXXXX"

# Ensure the testRunId is being correctly accessed from the environment variable
if ($null -eq $env:test_RunId -or $env:test_RunId -eq "") {
    Write-Error "The environment variable 'test.RunId' is not set or is empty."
    exit 1
}

$testRunId = $env:test_RunId
Write-Output "TestRunId: $testRunId"

# Prepare headers for REST API call
$patEncoded = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$headers = @{
    Authorization = "Basic $patEncoded"
    "Content-Type" = "application/json"
}

# Function to parse JUnit XML and get test outcomes
function Get-TestOutcomes {
    param (
        [string]$testResultsPath
    )
    $results = @()
    Write-Output "Parsing test results from path: $testResultsPath"

    $testResultFiles = Get-ChildItem -Path $testResultsPath -ErrorAction Stop
    foreach ($file in $testResultFiles) {
        Write-Output "Processing file: $($file.FullName)"
        [xml]$xml = Get-Content $file.FullName

        foreach ($testcase in $xml.testsuite.testcase) {
            $testCaseName = $testcase.name
            if ($null -eq $testCaseName -or $testCaseName -eq "") {
                Write-Error "Test case name is null or empty in file: $($file.FullName)"
                continue
            }

            $outcome = "Passed"
            if ($testcase.failure) {
                $outcome = "Failed"
            } elseif ($testcase.error) {
                $outcome = "Error"
            } elseif ($testcase.skipped) {
                $outcome = "NotExecuted"
            }

            $duration = [math]::Round([double]$testcase.time * 1000) # Convert seconds to milliseconds

            $result = @{
                name = $testCaseName
                outcome = $outcome
                durationInMs = $duration
            }

            $results += $result
        }
    }

    return $results
}

# Get test outcomes from JUnit XML
$newTestOutcomes = Get-TestOutcomes -testResultsPath $testResultsPath
Write-Output "New test outcomes: $($newTestOutcomes | ConvertTo-Json -Depth 10)"

# Ensure the third outcome is selected
if ($newTestOutcomes.Count -lt 3) {
    Write-Error "There are not enough test outcomes to select the third one."
    exit 1
}

# Select the third test outcome and add the necessary properties
$updateResultsPayload = $newTestOutcomes[2]
$updateResultsPayload.id = "100000"
$updateResultsPayload.state = "Completed"

# Encapsulate the payload in an array and convert to JSON
$updateResultsPayloadArray = @($updateResultsPayload)
$updateBody = $updateResultsPayloadArray | ConvertTo-Json -Depth 10

# Ensure the JSON format is as expected
Write-Output "Formatted JSON payload: $updateBody"

# Make the REST API call to update the test results
$updateUri = "https://dev.azure.com/$organization/$project/_apis/test/runs/$testRunId/results?api-version=6.0"
Write-Output "Update URI: $updateUri"
Write-Output "Updating test result with payload: $updateBody"

try {
    $response = Invoke-RestMethod -Uri $updateUri -Method Patch -Headers $headers -Body $updateBody -ErrorAction Stop

    if ($response -eq $null) {
        Write-Error "Failed to update test result"
    } else {
        Write-Output "Test result updated successfully"
    }
} catch {
    Write-Error "Error updating test result: $_"
}

# Mark the test run as completed with a comment
$completeRunUri = "https://dev.azure.com/$organization/$project/_apis/test/runs/$testRunId?api-version=6.0"
$body = @{
    state = "Completed"
    comment = "Automated tests have been executed and results updated."
} | ConvertTo-Json

Write-Output "Marking the test run as completed with a comment at: $completeRunUri"
Write-Output "Payload: $body"

try {
    $response = Invoke-RestMethod -Uri $completeRunUri -Method Patch -Headers $headers -Body $body -ErrorAction Stop

    if ($response -eq $null) {
        Write-Error "Failed to mark test run as completed"
    } else {
        Write-Output "Test run marked as completed successfully"
    }
} catch {
    Write-Error "Error marking test run as completed: $_"
}

# Write an output to the pipeline log
Write-Output "Test results have been updated and test run marked as completed for test run ID $testRunId"

I want the output of $updateBody in array of JSON objects

Sample

[
    {
        "name": "XXXX",
        "outcome": "XXXX",
        "durationInMs": XXXX,
        "id": "XXXX",
        "state": "XXXX"
    }
]

Can anyone help me on this with the required output ?

LEAVE A COMMENT