forked from jdhitsolutions/PSScriptTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashtableTools.ps1
More file actions
481 lines (419 loc) · 15.9 KB
/
hashtableTools.ps1
File metadata and controls
481 lines (419 loc) · 15.9 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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
Function Convert-HashtableString {
[cmdletbinding()]
[OutputType([System.Collections.Hashtable])]
Param(
[parameter(Mandatory, HelpMessage = "Enter your hashtable string", ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[string]$Text
)
Begin {
Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"
} #begin
Process {
$tokens = $null
$err = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$tokens, [ref]$err)
$data = $ast.find( { $args[0] -is [System.Management.Automation.Language.HashtableAst] }, $true)
if ($err) {
Throw $err
}
else {
$data.SafeGetValue()
}
}
End {
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
} #end
}
Function ConvertTo-HashTable {
[cmdletbinding()]
[OutputType([System.Collections.Specialized.OrderedDictionary])]
[OutputType([System.Collections.Hashtable])]
Param(
[Parameter(
Position = 0,
Mandatory,
HelpMessage = "Please specify an object",
ValueFromPipeline
)]
[ValidateNotNullorEmpty()]
[object]$InputObject,
[switch]$NoEmpty,
[string[]]$Exclude,
[switch]$Alphabetical,
[Parameter(HelpMessage = "Create an ordered hashtable instead of a plain hashtable.")]
[switch]$Ordered
)
Process {
<#
get type using the [Type] class because deserialized objects won't have
a GetType() method which is what I would normally use.
#>
$TypeName = [system.type]::GetTypeArray($InputObject).name
Write-Verbose "Converting an object of type $TypeName"
#get property names using Get-Member
$names = $InputObject | Get-Member -MemberType properties |
Select-Object -ExpandProperty name
if ($Alphabetical) {
Write-Verbose "Sort property names alphabetically"
$names = $names | Sort-Object
}
#define an empty hash table
if ($Ordered) {
Write-Verbose "Creating an ordered hashtable"
$hash = [ordered]@{ }
}
else {
$hash = @{ }
}
#go through the list of names and add each property and value to the hash table
$names | ForEach-Object {
#only add properties that haven't been excluded
if ($Exclude -notcontains $_) {
#only add if -NoEmpty is not called and property has a value
if ($NoEmpty -AND -Not ($inputobject.$_)) {
Write-Verbose "Skipping $_ as empty"
}
else {
Write-Verbose "Adding property $_"
$hash.Add($_, $inputobject.$_)
}
} #if exclude notcontains
else {
Write-Verbose "Excluding $_"
}
} #foreach
Write-Verbose "Writing the result to the pipeline"
Write-Output $hash
}#close process
}#end function
Function Convert-HashTableToCode {
[cmdletbinding(DefaultParameterSetName = "psd1")]
[alias("chc")]
[OutputType([system.string])]
Param(
[Parameter(Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullorEmpty()]
[hashtable]$Hashtable,
[Parameter(ParameterSetName = "psd1")]
[Alias("tab")]
[int]$Indent = 1,
[Parameter(ParameterSetName = "inline", HelpMessage = "Write the hashtable as an inline expression")]
[switch]$Inline
)
Begin {
Write-Verbose "Starting $($myinvocation.mycommand)"
if ($Inline) {
Write-Verbose "Creating an inline expression"
}
}
Process {
Write-Verbose "Processing a hashtable with $($hashtable.keys.count) keys"
$hashtable.GetEnumerator() | ForEach-Object -begin {
[string]$out = "@{"
if ($PSCmdlet.ParameterSetName -eq 'psd1') {
$out += "`n"
}
} -Process {
Write-Verbose "Testing value type $($_.value.gettype().name) for key $($_.key)"
#determine if the value needs to be enclosed in quotes
if ($_.value.gettype().name -match "Int|double") {
Write-Verbose "..is a numeric"
$value = $_.value
}
elseif ($_.value -is [array]) {
#assuming all the members of the array are of the same type
Write-Verbose "..is an array"
#test if an array of numbers otherwise treat as strings
if ($_.value[0].Gettype().name -match "int|double") {
$value = $_.value -join ','
}
else {
$value = "'{0}'" -f ($_.value -join "','")
}
}
elseif ($_.value -is [hashtable]) {
Write-Verbose "Creating nested entry"
$nested = Convert-HashTableToCode $_.value -Indent $($indent + 1)
$value = "$($nested)"
}
elseif ($_.value -is [scriptblock]) {
Write-Verbose "Parsing scriptblock"
$value = "{$($_.value)}"
}
else {
Write-Verbose "..defaulting as a string"
$value = "'$($_.value)'"
}
if ($inline) {
$out += "$($_.key) = $value;"
}
else {
$tabcount = "`t" * $Indent
$out += "$tabcount$($_.key) = $value `n"
}
} -end {
if ($inline) {
#strip off the last ;
$out = $out.remove($out.Length - 1)
$out += "}"
}
else {
$tabcount = "`t" * ($Indent - 1)
$out += "$tabcount}`n"
}
$out
}
} #process
End {
Write-Verbose "Ending $($myinvocation.mycommand)"
}
} #end function
Function Join-Hashtable {
[cmdletbinding()]
[OutputType([System.Collections.Hashtable])]
Param (
[hashtable]$First,
[hashtable]$Second,
[switch]$Force
)
#create clones of hashtables so originals are not modified
$Primary = $First.Clone()
$Secondary = $Second.Clone()
#check for any duplicate keys
$duplicates = $Primary.keys | Where-Object { $Secondary.ContainsKey($_) }
if ($duplicates) {
foreach ($item in $duplicates) {
if ($force) {
#force primary key, so remove secondary conflict
$Secondary.Remove($item)
}
else {
Write-Host "Duplicate key $item" -ForegroundColor Yellow
Write-Host "A $($Primary.Item($item))" -ForegroundColor Yellow
Write-Host "B $($Secondary.Item($item))" -ForegroundColor Yellow
$r = Read-Host "Which key do you want to KEEP [AB]?"
if ($r -eq "A") {
$Secondary.Remove($item)
}
elseif ($r -eq "B") {
$Primary.Remove($item)
}
Else {
Write-Warning "Aborting operation"
Return
}
} #else prompt
}
}
#join the two hash tables
$Primary + $Secondary
} #end Join-Hashtable
Function Convert-CommandtoHashtable {
[cmdletbinding()]
[OutputType("Hashtable")]
Param(
[Parameter(Mandatory)]
[ValidateNotNullorEmpty()]
#"Enter a PowerShell expression with full parameter names"
[string]$Text
)
Set-StrictMode -Version latest
New-Variable astTokens -force
New-Variable astErr -force
#trim spaces
$Text = $Text.trim()
Write-Verbose "Converting $text"
$ast = [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$astTokens, [ref]$astErr)
#resolve the command name
$cmdType = Get-Command $asttokens[0].text
if ($cmdType.CommandType -eq 'Alias') {
$cmd = $cmdType.ResolvedCommandName
}
else {
$cmd = $cmdType.Name
}
#last item is end of input token
$r = for ($i = 1; $i -lt $astTokens.count - 1 ; $i++) {
if ($astTokens[$i].ParameterName) {
$p = $astTokens[$i].ParameterName
$v = ""
#check next token
if ($astTokens[$i + 1].Kind -match 'Parameter|EndOfInput') {
#the parameter must be a switch
$v = "`$True"
}
else {
While ($astTokens[$i + 1].Kind -notmatch 'Parameter|EndOfInput') {
$i++
#test if value is a string and if it is quoted, if not include quotes
#if ($astTokens[$i].Kind -eq "Identifier" -AND $astTokens[$i].Text -notmatch """\w+.*""" -AND $astTokens[$i].Text -notmatch "'\w+.*'") {
if ($astTokens[$i].Text -match "\D" -AND $astTokens[$i].Text -notmatch """\w+.*""" -AND $astTokens[$i].Text -notmatch "'\w+.*'") {
#ignore commas and variables
if ($astTokens[$i].Kind -match 'Comma|Variable') {
$value = $astTokens[$i].Text
}
else {
#Assume text and quote it
$value = """$($astTokens[$i].Text)"""
}
}
else {
$value = $astTokens[$i].Text
}
$v += $value
} #while
}
#don't add a line return if this is going to be the last item
if ($i + 1 -ge $astTokens.count - 1) {
" $p = $v"
}
else {
" $p = $v`n"
}
} #if ast parameter name
} #for
$hashtext = @"
`$paramHash = @{
$r
}
$cmd @paramHash
"@
$hashtext
}
Function Rename-HashTable {
[cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Pipeline")]
[alias("rht")]
Param(
[parameter(
Position = 0,
Mandatory,
HelpMessage = "Enter the name of your hash table variable without the `$",
ParameterSetName = "Name"
)]
[ValidateNotNullorEmpty()]
[string]$Name,
[parameter(
Position = 0,
Mandatory,
ValueFromPipeline,
ParameterSetName = "Pipeline"
)]
[ValidateNotNullorEmpty()]
[object]$InputObject,
[parameter(
Position = 1,
Mandatory,
HelpMessage = "Enter the existing key name you want to rename")]
[ValidateNotNullorEmpty()]
[string]$Key,
[parameter(position = 2, Mandatory, HelpMessage = "Enter the NEW key name"
)]
[ValidateNotNullorEmpty()]
[string]$NewKey,
[switch]$Passthru,
[ValidateSet("Global", "Local", "Script", "Private", 0, 1, 2, 3)]
[ValidateNotNullOrEmpty()]
[string]$Scope = "Global"
)
Begin {
Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"
Write-Verbose "using parameter set $($PSCmdlet.ParameterSetName)"
}
Process {
Write-Verbose "PSBoundparameters"
Write-Verbose $($PSBoundParameters | Out-String)
#validate Key and NewKey are not the same
if ($key -eq $NewKey) {
Write-Warning "The values you specified for -Key and -NewKey appear to be the same. Names are NOT case-sensitive"
#bail out
Return
}
Try {
#validate variable is a hash table
if ($InputObject) {
#create a completely random name to avoid any possible naming collisions
$name = [system.io.path]::GetRandomFileName()
Write-Verbose "Creating temporary hashtable ($name) from pipeline input"
Set-Variable -Name $name -Scope $scope -value $InputObject -WhatIf:$False
$passthru = $True
}
else {
Write-Verbose "Using hashtable variable $name"
}
Write-Verbose (Get-Variable -Name $name -Scope $scope | Out-String)
Write-Verbose "Validating $name as a hashtable in $Scope scope."
#get the variable
$var = Get-Variable -Name $name -Scope $Scope -ErrorAction Stop
Write-Verbose "Detected a $($var.value.GetType().fullname)"
Write-Verbose "Testing for key $key"
if (-Not $var.value.Contains($key)) {
Write-Warning "Failed to find the key $key in the hashtable."
#bail out
Return
}
if ( $var.Value -is [hashtable]) {
#create a temporary copy
Write-Verbose "Cloning a temporary hashtable"
<#
Use the clone method to create a separate copy.
If you just assign the value to $temphash, the
two hash tables are linked in memory so changes
to $tempHash are also applied to the original
object.
#>
$tempHash = $var.Value.Clone()
if ($pscmdlet.ShouldProcess($NewKey, "Replace key $key")) {
Write-Verbose "Writing the new hashtable to variable named $hashname"
#create a key with the new name using the value from the old key
Write-Verbose "Adding new key $newKey to the temporary hashtable"
$tempHash.Add($NewKey, $tempHash.$Key)
#remove the old key
Write-Verbose "Removing $key"
$tempHash.Remove($Key)
#write the new value to the variable
Write-Verbose "Writing the new hashtable to variable named $Name"
Write-Verbose ($tempHash | Out-String)
Set-Variable -Name $Name -Value $tempHash -Scope $Scope -Force -PassThru:$Passthru |
Select-Object -ExpandProperty Value
}
}
elseif ($var.value -is [System.Collections.Specialized.OrderedDictionary]) {
Write-Verbose "Processing as an ordered dictionary"
$varHash = $var.value
#find the index number of the existing key
$i = -1
Do {
$i++
} Until (($varHash.GetEnumerator().name)[$i] -eq $Key)
#save the current value
$val = $varhash.item($i)
if ($pscmdlet.ShouldProcess($NewKey, "Replace key $key at $i")) {
#remove at the index number
$varhash.RemoveAt($i)
#insert the new value at the index number
$varhash.Insert($i, $NewKey, $val)
Write-Verbose "Writing the new hashtable to variable named $name"
Write-Verbose ($varHash | Out-String)
Set-Variable -Name $name -Value $varhash -Scope $Scope -Force -PassThru:$Passthru |
Select-Object -ExpandProperty Value
}
}
else {
Write-Warning "The variable $name does not appear to be a hash table or ordered dictionaryBet"
}
} #Try
Catch {
Write-Warning "Failed to find a variable with a name of $Name. $($_.exception.message)."
}
Write-Verbose "Rename complete."
} #Process
End {
#clean up any temporary variables
if ($InputObject) {
Write-Verbose "Removing temporary variable $name"
Remove-Variable -name $Name -Scope $scope -WhatIf:$False
}
Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
} #end
} #end Rename-Hashtable