Helpers/Write-PowerShellHashTable.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
function Write-PowerShellHashtable {
    <#
    .Synopsis
        Takes an creates a script to recreate a hashtable
    .Description
        Allows you to take a hashtable and create a hashtable you would embed into a script.
         
        Handles nested hashtables and indents nested hashtables automatically.
    .Parameter inputObject
        The hashtable to turn into a script
    .Parameter scriptBlock
        Determines if a string or a scriptblock is returned
    .Example
        # Corrects the presentation of a PowerShell hashtable
        @{Foo='Bar';Baz='Bing';Boo=@{Bam='Blang'}} | Write-PowerShellHashtable
    .Outputs
        [string]
    .Outputs
        [ScriptBlock]
    .Link
        about_hash_tables
    #>
    
    [OutputType([string], [ScriptBlock])]
    param(
    [Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [PSObject]
    $InputObject,

    # Returns the content as a script block, rather than a string
    [Alias('ScriptBlock')]
    [switch]$AsScriptBlock,

    [Switch]$Sort
    )

    process {
        $callstack = @(foreach ($_ in (Get-PSCallStack)) {
            if ($_.Command -eq "Write-PowerShellHashtable") {
                $_
            }
        })
        $depth = $callStack.Count
        if ($inputObject -isnot [Hashtable]) {
            
            $newInputObject = @{
                PSTypeName=@($inputobject.pstypenames)[-1]
            }
            foreach ($prop in $inputObject.psobject.properties) {                
                $newInputObject[$prop.Name] = $prop.Value
            }
            $inputObject = $newInputObject
        }
        
        if ($inputObject -is [Hashtable]) {
            #region Indent
            $scriptString = ""
            $indent = $depth * 4        
            $scriptString+= "@{
"

            #endregion Indent
            #region Include
            $items = $inputObject.GetEnumerator()

            if ($Sort) {
                $items = $items | Sort-Object Key
            }
            

            foreach ($kv in $items) {
                $scriptString+=" " * $indent
                
                $keyString = "$($kv.Key)"
                if ($keyString.IndexOfAny(" _.#-+:;()'!?^@#$%&".ToCharArray()) -ne -1) {
                    if ($keyString.IndexOf("'") -ne -1) {
                        $scriptString+="'$($keyString.Replace("'","''"))'="
                    } else {
                        $scriptString+="'$keyString'="
                    }                    
                } elseif ($keyString) {
                    $scriptString+="$keyString="
                }
                                
                
                
                $value = $kv.Value
                # Write-Verbose "$value"
                if ($value -is [string]) {
                
                    $value = "'"  + $value.Replace("'","''").Replace("’", "’’").Replace("‘", "‘‘") + "'"
                } elseif ($value -is [ScriptBlock]) {
                    $value = "{$value}"
                } elseif ($value -is [switch]) {
                    $value = if ($value) { '$true'} else { '$false' }
                } elseif ($value -is [bool]) {
                    $value = if ($value) { '$true'} else { '$false' }
                } elseif ($value -and $value.GetType -and ($value.GetType().IsArray -or $value -is [Collections.IList])) {
                    $value = foreach ($v in $value) {
                        if ($v -is [Hashtable]) {
                            Write-PowerShellHashtable $v
                        } elseif ($v -is [Object] -and $v -isnot [string]) {
                            Write-PowerShellHashtable $v
                        } else {
                            ("'"  + "$v".Replace("'","''").Replace("’", "’’").Replace("‘", "‘‘") + "'")
                        }
                    }
                    $oldOfs = $ofs 
                    $ofs = ",
$(' ' * ($indent + 4))"

                    $value = "$value"
                    $ofs = $oldOfs
                } elseif ($value -as [Hashtable[]]) {
                    $value = foreach ($v in $value) {
                        Write-PowerShellHashtable $v
                    }
                    $value = $value -join ","
                } elseif ($value -is [Hashtable]) {
                    $value = "$(Write-PowerShellHashtable $value)"
                } elseif ($value -as [Double]) {
                    $value = "$value"
                } else {
                    $valueString = "'$value'" 
                    if ($valueString[0] -eq "'" -and 
                        $valueString[1] -eq "@" -and 
                        $valueString[2] -eq "{") {
                        $value = Write-PowerShellHashtable -InputObject $value                    
                    } else {
                        $value = $valueString
                    }
                    
                }                                
               $scriptString+="$value
"

            }
            $scriptString += " " * ($depth - 1) * 4          
            $scriptString += "}"     
            if ($AsScriptBlock) {
                [ScriptBlock]::Create($scriptString)
            } else {
                $scriptString
            }
            #endregion Include
        }          
   }
}