-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConvertTo-HashTable.ps1
More file actions
93 lines (78 loc) · 2.86 KB
/
ConvertTo-HashTable.ps1
File metadata and controls
93 lines (78 loc) · 2.86 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
function ConvertTo-HashTable {
<#
.SYNOPSIS
Converts text file content like a PSD1 file into a hashtable.
.DESCRIPTION
Convert raw text contained in a PSD1 file and
creates a hashtable object on the pipeline, after
running a basic verification routine on the logic in the file.
.PARAMETER Path
A file containing the hash table, ex: PSD1 file
.PARAMETER HashTableContent
The hashtable represented as a string (or array)
.PARAMETER Force
Does not check the loic before executing the code contained in the PSD1 file.
.EXAMPLE
$hash = ConvertTo-HashTable -HashTableContent (Get-Content $filepath)
.EXAMPLE
$hash = Get-Content $filepath | ConvertTo-HashTable
.EXAMPLE
$hash = ConvertTo-HashTable -Path ./filename.psd1
#>
[CmdletBinding(DefaultParameterSetName='byContent')]
param (
# The file containing the hash table, ex: PSD1 file
[Parameter(ParameterSetName='byPath')]
[ValidateScript({Test-Path $_})]
[string]
$Path,
# The hashtable represented as a string (array)
[Parameter(ValueFromPipeline,ParameterSetName='byContent')]
[string[]]
$HashTableContent,
# Does not check the logic before executing the code contained in the PSD1 file.
[Parameter()]
[switch]
$Force
)
begin {
$Content = New-Object -TypeName System.Collections.ArrayList
[string[]]$allowedCommands = @(
'New-TimeSpan'
'Get-Date'
)
[string[]]$allowedVariables = @()
[bool]$allowEnvVariables = $false
}
process {
if ($PSCmdlet.ParameterSetName -eq 'byContent') {
foreach ($line in $HashTableContent) {
[void]($Content.Add($line))
}
} elseif ($PSCmdlet.ParameterSetName -eq 'byPath') {
Try {
Write-Verbose "Content being parsed from config file: [$($Path)]."
$Content = Get-Content -Path $Path -ErrorAction Stop
} Catch {
throw "Unable to parse file content: $($_.exception.message)"
}
}
}
end {
$rawContent = @($Content).Where({$_ -notmatch '^#'})
$strContent = $rawContent -join "`n"
# Define a hashtable for all tasks (KEY=pathToParentFolder, VALUE=retentionInDays)
Try {
$scriptBlock = [scriptblock]::Create($strContent)
if (-not $Force.IsPresent) {
$scriptBlock.CheckRestrictedLanguage(
$allowedCommands, $allowedVariables, $allowEnvVariables
)
}
& $scriptBlock
} Catch {
Write-Warning "$($_.exception.message)"
throw "Unable to execute parsed text as a scriptblock!"
}
}
}#END: function ConvertTo-HashTable {}