-
Notifications
You must be signed in to change notification settings - Fork 29
/
ConvertTo-PowerShell.ps1
299 lines (286 loc) · 9.69 KB
/
ConvertTo-PowerShell.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
<#
.SYNOPSIS
Serializes complex content into PowerShell literals.
.INPUTS
System.Object (any object) to serialize.
.OUTPUTS
System.String containing the object serialized to PowerShell literal statements.
.FUNCTIONALITY
Data formats
.EXAMPLE
4096LMB |ConvertTo-PowerShell.ps1
4LGB
.EXAMPLE
ConvertFrom-Json '[{"a":1,"b":2,"c":{"d":"\/Date(1490216371478)\/","e":null}}]' |ConvertTo-PowerShell.ps1
[pscustomobject]@{
a = 1L
b = 2L
c = [pscustomobject]@{
d = [datetime]'2017-03-22T20:59:31'
e = $null
}
}
#>
#Requires -Version 3
[CmdletBinding(DefaultParameterSetName='GenerateKey')][OutputType([string])] Param(
# An array, hash, object, or value type that can be represented as a PowerShell literal.
[Parameter(Position=0,ValueFromPipeline=$true)] $Value,
# The starting indent value. You can probably ignore this.
[string] $Indent = '',
# The string to use for incremental indentation.
[string] $IndentBy = "`t",
# The line ending sequence to use.
[string] $Newline = [environment]::NewLine,
# Indicates the first line has already been indented. You can probably ignore this.
[switch] $SkipInitialIndent,
# The maximum width of string literals.
[ValidateRange(1,0xFFFF)][uint16] $Width = 80,
<#
Generates a key to use for encrypting credential and secure string literals.
If this is omitted, credentials will be encrypted using DPAPI, which will only be
decryptable on the same Windows machine where they were encrypted.
#>
[Parameter(ParameterSetName='GenerateKey')][Alias('PortableKey')][switch] $GenerateKey,
<#
The key to use for encrypting credentials and secure strings, as a secure string to be
encoded into UTF-8 bytes.
#>
[Parameter(ParameterSetName='SecureKey',Mandatory=$true)][securestring] $SecureKey,
<#
A credential containing a password (the username is ignored) to be used for encrypting
credentials and secure strings, after encoding to UTF-8 bytes.
#>
[Parameter(ParameterSetName='Credential',Mandatory=$true)][pscredential] $Credential,
# The key to use for encrypting credentials and secure strings, as a byte array.
[Parameter(ParameterSetName='KeyBytes',Mandatory=$true)][byte[]] $KeyBytes
)
Begin
{
$Script:OFS = "$Newline$Indent"
$Local:PSDefaultParameterValues = @{
'ConvertTo-PowerShell.ps1:Indent' = "$Indent$IndentBy"
'ConvertTo-PowerShell.ps1:IndentBy' = $IndentBy
'ConvertTo-PowerShell.ps1:Width' = $Width
}
$itab = if($SkipInitialIndent){''}else{$Indent}
$tab = $Indent
$tabtab = "$Indent$IndentBy"
$units = @{ 1LKB = 'KB'; 1LMB = 'MB'; 1LGB = 'GB'; 1LTB = 'TB'; 1LPB = 'PB' }
if($GenerateKey)
{
[byte[]] $KeyBytes = Get-RandomBytes.ps1 32
"[byte[]]`$key = $($KeyBytes -join ',')"
}
elseif($SecureKey)
{
$Credential = New-Object pscredential 'SecureKey',$SecureKey
}
if($Credential)
{
[byte[]] $salt = Get-RandomBytes.ps1 8
$hash = New-Object Security.Cryptography.Rfc2898DeriveBytes `
([Text.Encoding]::UTF8.GetBytes(($Credential.Password |ConvertFrom-SecureString -AsPlainText))),$salt,
(Get-Random 9999 -Minimum 1000)
$iterations = $hash.IterationCount
[byte[]] $salt = $hash.Salt
[byte[]] $KeyBytes = $hash.GetBytes(32)
$hash.Dispose(); $hash = $null
$creduser = $Credential.UserName -replace "'","''"
"`$hash = New-Object Security.Cryptography.Rfc2898DeriveBytes ``"
" ([Text.Encoding]::UTF8.GetBytes(((Get-Credential '$creduser').Password |ConvertFrom-SecureString -AsPlainText)),"
" ($($salt -join ',')),$iterations"
"[byte[]]`$key = `$hash.GetBytes(32)"
"`$hash.Dispose(); `$hash = `$null"
}
if($KeyBytes)
{
$Local:PSDefaultParameterValues['ConvertTo-PowerShell.ps1:Key'] = $KeyBytes
$keyopt = ' -Key $key'
$dpapiwarn = ''
$Script:PSDefaultParameterValues['ConvertFrom-SecureString:Key'] = $KeyBytes
}
else
{
$keyopt = ''
$dpapiwarn = " # using DPAPI, only valid for $env:UserName on $env:ComputerName as of $(Get-Date)"
}
function Format-PSString([string]$string)
{
$q,$string =
if($string -match '[\0\a\b\f\t\v]')
{
'"'
$string -replace '$','`$' -replace '`','``' -replace '"','`"' -replace "`0",'`0' -replace "`a",'`a' -replace "`b",'`b' -replace "`f",'`f' -replace "`t",'`t' -replace "`v",'`v'
}
else
{
"'"
$string -replace "'","''"
}
if($string -match '\n|\r') {"@$q$Newline$string$Newline$q@"}
else {"$itab$q$string$q"}
}
filter Format-WrapString
{
Write-Debug "Format-WrapString '$_' -Width $Width"
for($i = 0; ($i+$Width) -lt $_.Length; $i += $Width) {$_.Substring($i,$Width)}
if($_.Length % $Width) {$_.Substring($_.Length - ($_.Length % $Width))}
}
$typealias = Get-TypeAccelerators.ps1 -DictionaryKey TypeName
filter Format-ParameterType
{
$type = $_.ParameterType.FullName
if($typealias.ContainsKey($type)) {$type = $typealias[$type]}
"[$type]"
}
filter Format-ParameterAttribute
{
Import-Variables.ps1 $_
$name = $_.GetType().Name -replace 'Attribute\z',''
switch($name)
{
Parameter
{
$props = @()
if($ParameterSetName -ne '__AllParameterSets') {$props += "ParameterSetName=$ParameterSetName"}
if($Position -ne [int]::MinValue) {$props += "Position=$Position"}
'Mandatory','ValueFromPipeline','ValueFromPipelineByPropertyName','ValueFromRemainingArguments' |
Get-Variable -ErrorAction Ignore |
Where-Object {$_.Value} |
ForEach-Object {$props += "$($_.Name)=`$$($_.Value.ToString().ToLower())"}
if($props){"[$name($($props -join ','))]"} else {''}
}
Alias {"[Alias($(($AliasNames |ConvertTo-PowerShell.ps1 -SkipInitialIndent) -join ','))]"}
ValidateCount {"[$name($MinLength,$MaxLength)]"}
ValidateDrive {"[$name($(($ValidRootDrives |ConvertTo-PowerShell.ps1 -SkipInitialIndent) -join ','))]"}
ValidateLength {"[$name($MinLength,$MaxLength)]"}
ValidatePattern {"[$name('$($RegexPattern -replace "'","''")')]"}
ValidateRange {"[$name($MinRange,$MaxRange)]"}
ValidateScript {"[$name({$ScriptBlock})]"}
ValidateSet {"[$name($(($ValidValues |ConvertTo-PowerShell.ps1 -SkipInitialIndent) -join ','))]"}
default {"[$name()]"}
}
}
function Format-Child($InputObject,[switch]$UseKeys)
{
if($null -eq $InputObject) {return}
$(if($UseKeys){$InputObject.Keys}else{Get-Member -InputObject $InputObject -MemberType Properties |Select-Object -ExpandProperty Name}) |
Where-Object {$_ -notmatch '\W'} |
ForEach-Object {"$IndentBy$_ = $(ConvertTo-PowerShell.ps1 $InputObject.$_ -Indent "$tab$IndentBy" -SkipInitialIndent)"}
}
}
Process
{
if($null -eq $Value)
{ "$itab`$null" }
elseif($Value -is [bool])
{ "$itab`$$Value" }
elseif([int],[long],[byte],[decimal],[double],[float],[short],[sbyte],[uint16],[uint32],[uint64],[bigint] -contains $Value.GetType())
{
$number,$unit = $Value,''
if($number -ge 1KB)
{
for($magnitude = 1LKB; $magnitude -le 1PB -and !($Value % $magnitude); $magnitude *= 1LKB)
{
$number = $Value / $magnitude
$unit = $units[$magnitude]
}
}
$suffix,$prefix =
if($Value -is [int]) {}
elseif($Value -is [long]) { 'L' }
elseif($Value -is [decimal]) { 'd' }
elseif($Value -is [bigint])
{
if($PSVersionTable.PSVersion.Major -lt 7) { "'","[bigint]'" }
else { 'n' }
}
elseif($PSVersionTable.PSVersion.Major -lt 7) { '',"[$($Value.GetType().Name)]" }
else
{
switch($Value.GetType().Name)
{
Byte { 'uy' }
Int16 { 's' }
SByte { 'y' }
UInt16 { 'us' }
UInt32 { 'u' }
UInt64 { 'ul' }
}
}
"$itab$prefix$number$suffix$unit"
}
elseif([guid],[timespan],[char] -contains $Value.GetType())
{ "$itab[$($Value.GetType().Name)]'$Value'" }
elseif($Value -is [datetimeoffset])
{ "$itab[datetimeoffset]'$($Value.ToString('yyyy-MM-dd\THH:mm:ss.fffffzzzz'))'" }
elseif($Value -is [datetime])
{ "$itab[datetime]'$(Get-Date -Date $Value -f yyyy-MM-dd\THH:mm:ss)'" }
elseif($Value -is [enum])
{ "$itab([$($Value.GetType().FullName)]::$Value)" }
elseif($Value -is [string])
{ Format-PSString $Value }
elseif($Value -is [array])
{@"
$itab@(
$($Value |ForEach-Object {ConvertTo-PowerShell.ps1 $_})
$tab)
"@}
elseif($Value -is [securestring])
{
$password = (ConvertFrom-SecureString $Value |Format-WrapString) -join "' +$Newline${tabtab}'"
"(ConvertTo-SecureString ($Newline${tabtab}'$password')$keyopt)$dpapiwarn"
}
elseif($Value -is [pscredential])
{
Write-Debug "Credential $($Value.UserName)"
$username = "'$($Value.UserName -replace "'","''")'"
$password =
if(!$Value.Password) {'$null'}
else
{
$p = (ConvertFrom-SecureString $Value.Password |Format-WrapString) -join "' +$Newline${tabtab}'"
"(ConvertTo-SecureString ($Newline${tabtab}'$p')$keyopt)"
}
"${itab}New-Object pscredential $username,$password$dpapiwarn"
}
elseif($Value -is [Management.Automation.RuntimeDefinedParameterDictionary])
{@"
${itab}Param(
$(($Value.GetEnumerator() |ForEach-Object {"$tabtab$(ConvertTo-PowerShell.ps1 $_.Value)"}) -join ',')
$tab)
"@}
elseif($Value -is [Management.Automation.RuntimeDefinedParameter])
{@"
$($Value.Attributes |Format-ParameterAttribute)
$itab$($Value |Format-ParameterType) `$$($Value.Name)
"@}
elseif($Value -is [ScriptBlock])
{ "{$Value}" }
elseif($Value -is [Collections.Specialized.OrderedDictionary])
{@"
$itab[ordered]@{
$tab$(Format-Child $Value -UseKeys)
$tab}
"@}
elseif($Value -is [Hashtable])
{@"
$itab@{
$tab$(Format-Child $Value -UseKeys)
$tab}
"@}
elseif($Value -is [xml])
{ "[xml]$(Format-PSString $Value.OuterXml)" }
elseif($Value -is [PSObject])
{@"
$itab[pscustomobject]@{
$tab$(Format-Child $Value)
$tab}
"@}
else
{@"
$itab@{
$tab$(Format-Child $Value)
$tab}
"@}
}