ConvertTo-Json how to keep an order of the hash table fields
Asked Answered
K

1

6

I am running the following PowerShell code, I need to keep the order of the original hash table keys.

function New-GetServiceConnectionTask( $serviceConnectionId)
{
    @{
        environment      = @{ }
        taskId           = '0a9fdc5e-3f3a-4d3d-9f63-a4f007f9a1fe'
        version          = "1.*"
        name             = 'Get Service Endpoint Credentials'
        refName          = ''
        enabled          = $true
        alwaysRun        = $false
        continueOnError  = $false
        timeoutInMinutes = 0
        definitionType   = 'task'
        overrideInputs   = @{ }
        condition        = 'succeeded()'
        inputs           = @{
            connectedServiceNameARM = $serviceConnectionId
        }
    }
}
New-GetServiceConnectionTask xxx | ConvertTo-Json -Depth 99 

The function returns

{
    "version": "1.*",
    "refName": "",
    "definitionType": "task",
    "overrideInputs": {},
    "name": "Get Service Endpoint Credentials",
    "environment": {},
    "inputs": {
        "connectedServiceNameARM": "xxx"
    },
    "timeoutInMinutes": 0,
    "taskId": "0a9fdc5e-3f3a-4d3d-9f63-a4f007f9a1fe",
    "enabled": true,
    "condition": "succeeded()",
    "continueOnError": false,
    "alwaysRun": false
}

Is there any option to keep the order of the original hash table keys?

Kaspar answered 14/5, 2020 at 18:21 Comment(0)
K
21

You can create an ordered hash by including [ordered] in front of the @ symbol like this:

[ordered]@{
    environment      = @{ }
    taskId           = '0a9fdc5e-3f3a-4d3d-9f63-a4f007f9a1fe'
    version          = "1.*"
    name             = 'Get Service Endpoint Credentials'
    refName          = ''
    enabled          = $true
    alwaysRun        = $false
    continueOnError  = $false
    timeoutInMinutes = 0
    definitionType   = 'task'
    overrideInputs   = @{ }
    condition        = 'succeeded()'
    inputs           = @{
        connectedServiceNameARM = $serviceConnectionId
    }
}
Kartis answered 14/5, 2020 at 18:27 Comment(1)
Note you may need to add [ordered] in front of all the @ symbols, not just the root level.Fanlight

© 2022 - 2024 — McMap. All rights reserved.