internal/ConvertTo-OrderedDictionary.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function ConvertTo-OrderedDictionary
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $InputObject
    )

    process
    {
        if($InputObject){
            if($InputObject -is [array]){
                $outputArray = @()
                foreach($item in $InputObject){
                    $outputArray += ConvertTo-OrderedDictionary $item
                }
                return $outputArray
            }
            elseif($InputObject -is [hashtable]){ 
                $outputObject = [ordered]@{}
                foreach ($Item in ($InputObject.GetEnumerator() | Sort-Object -Property Key)) {
                    if($Item){
                        $value = Get-ObjectProperty $Item 'Value'
                        if($value -is [hashtable]){ #if child is a hashtable, sort it too
                            $Item.Value = ConvertTo-OrderedDictionary $value
                        }
                    }
                    $outputObject[$Item.Key] = $Item.Value
                }
                return $outputObject
            }
        }
        else {
            return $InputObject
        }
    }
}