Public/Utils/Convert-HashtableToString.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
39
40
41
42
43
44
45
46
47
48
49
50
function Convert-HashtableToString {

    <#
    .SYNOPSIS
    Converts hashtable or any other dictionary to a serializable string. It also supports nested hashtables.

    .EXAMPLE
    Convert-HashtableToString -Hashtable @{'key' = 'value'; 'keyNested' = @{'a' = 'b'}}

        @{'key'='value'; 'keyNested'=@{'a'='b'; }; }
    #>


    [CmdletBinding()]
    [OutputType([string])]
    param(
        # Hashtable to convert.
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.Collections.IDictionary]
        $Hashtable
    )

    begin {
    }

    process {
        $sb = New-Object -TypeName System.Text.StringBuilder
        [void]($sb.Append('@{'))
        foreach ($entry in $Hashtable.GetEnumerator()) {

            $key = $entry.Key -replace "'", "''"
            $key = "'$key'"
            $value = $entry.Value
            if ($value -is [System.Collections.IDictionary]) {
                $value = Convert-HashtableToString -Hashtable $value
            }
            else {
                $value = $value -replace "'", "''"
                $value = "'$value'"
            }

            [void]($sb.Append("$key=$value; "))
        }
        [void]($sb.Append('}'))

        return $sb.ToString()
    }

    end {
    }
}