Search code examples
powershellhashtable

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


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?


Solution

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