forked from microsoft/security-devops-azdevops
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertTo-Hashtable.psm1
More file actions
120 lines (102 loc) · 3.15 KB
/
Copy pathConvertTo-Hashtable.psm1
File metadata and controls
120 lines (102 loc) · 3.15 KB
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
# Copyright (c) Microsoft Corporation. All rights reserved.
<#
.SYNOPSIS
Recursively converts PSCustomObjects inside of an array to Hashtables.
#>
Function Convert-HashtablesInArrays
{
[OutputType([Array])]
Param
( # Parameter help description
[Parameter(Position=0)]
[Array] $Array,
[Parameter(Position=1)]
[System.Int32] $Depth = 5
)
if ($Array -eq $null)
{
Write-Output $null
return
}
$convertedArray = @()
$nextDepth = $Depth - 1
foreach ($object in $Array)
{
$convertedObject = $object
if ($nextDepth -gt 0)
{
# Continue converting PSCustomObjects recursively
switch -regex ($object.GetType())
{
'.*Object$'
{
$convertedObject = ConvertTo-Hashtable -Object $object -Depth $nextDepth
break
}
'.*Array|.*\[\]'
{
$convertedObject = [object[]] (Convert-HashtablesInArrays -Array $object -Depth $nextDepth)
break
}
}
}
$convertedArray += ,$convertedObject
}
Write-Output $convertedArray
}
<#
.SYNOPSIS
Recursively converts a PSCustomObject and it's properties to Hashtables.
.NOTES
Unlike Hashtables, PSCustomObjects are difficult to add to once they are created.
When using ConvertFrom-Json to read json config files, PSCustomObjects are returned.
These objects, although not immutable, are hard to work with.
By converting them to Hashtables, they will be easier to diff, merge, and work with.
#>
Function ConvertTo-Hashtable
{
[OutputType([Hashtable])]
Param
(
[Parameter(Position=0)]
[AllowNull()]
[PSObject] $Object,
[Parameter(Position=1)]
[ValidateRange(0, [System.Int32]::MaxValue)]
[System.Int32] $Depth = 5
)
if ($Object -eq $null)
{
Write-Output $null
return
}
$hashtable = @{}
$nextDepth = $Depth - 1
foreach ($baseProperty in $Object.PSObject.Properties)
{
$convertedProperty = $baseProperty.Value
if ($nextDepth -gt 0) # -gt 0)
{
# Continue converting PSCustomObjects recursively
switch -regex ($baseProperty.Value.GetType())
{
'.*Object$'
{
$convertedProperty = ConvertTo-Hashtable -Object $baseProperty.Value -Depth $nextDepth
break
}
'.*Array|.*\[\]'
{
$convertedProperty = [object[]] (Convert-HashtablesInArrays -Array $baseProperty.Value -Depth $nextDepth)
break
}
}
}
$hashtable[$baseProperty.Name] = $convertedProperty
}
Write-Output $hashtable
}
Export-ModuleMember -Function @(
'ConvertTo-Hashtable',
'Convert-HashtablesInArrays'
)