Skip to content

Commit bd99f63

Browse files
committed
Import module
1 parent a0a4fba commit bd99f63

File tree

4 files changed

+68
-147
lines changed

4 files changed

+68
-147
lines changed

extensions/powershell/convert-resource.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ param (
77
begin {
88
$lines = [System.Collections.Generic.List[string]]::new()
99

10-
$scriptModule = Import-Module "$PSScriptRoot/convertDscResource.psd1" -Force -PassThru -ErrorAction Ignore
10+
$scriptModule = Import-Module "$PSScriptRoot/convertDscResource.psd1" -Force -PassThru -WarningAction SilentlyContinue -ErrorAction Stop
1111
}
1212

1313
process {

extensions/powershell/convertDscResource.psm1

Lines changed: 65 additions & 139 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
$Script:IsPowerShellCore = $PSVersionTable.PSEdition -eq 'Core'
22

3-
if ($Script:IsPowerShellCore)
4-
{
5-
if ($IsWindows)
6-
{
3+
if ($Script:IsPowerShellCore) {
4+
if ($IsWindows) {
75
Import-Module -Name 'PSDesiredStateConfiguration' -RequiredVersion 1.1 -UseWindowsPowerShell -WarningAction SilentlyContinue
86
}
97
Import-Module -Name 'PSDesiredStateConfiguration' -MinimumVersion 2.0.7 -Prefix 'Pwsh' -WarningAction SilentlyContinue
8+
} else {
9+
Import-Module -Name 'PSDesiredStateConfiguration' -RequiredVersion 1.1 -WarningAction SilentlyContinue
1010
}
1111

1212
function Write-DscTrace {
@@ -22,8 +22,7 @@ function Write-DscTrace {
2222
$host.ui.WriteErrorLine($trace)
2323
}
2424

25-
function Build-DscConfigDocument
26-
{
25+
function Build-DscConfigDocument {
2726
[CmdletBinding()]
2827
[OutputType([System.Collections.Specialized.OrderedDictionary])]
2928
param
@@ -42,17 +41,15 @@ function Build-DscConfigDocument
4241
# convert object to hashtable(s)
4342
$dscObjects = ConvertTo-DscObject @PSBoundParameters -ErrorAction SilentlyContinue
4443

45-
if (-not $dscObjects -or $dscObjects.Count -eq 0)
46-
{
44+
if (-not $dscObjects -or $dscObjects.Count -eq 0) {
4745
"No DSC objects found in the provided content." | Write-DscTrace -Operation Error
4846
exit 1
4947
}
5048

5149
# store all resources in variables
5250
$resources = [System.Collections.Generic.List[object]]::new()
5351

54-
foreach ($dscObject in $dscObjects)
55-
{
52+
foreach ($dscObject in $dscObjects) {
5653
$resource = [PSCustomObject]@{
5754
name = $dscObject.ResourceInstanceName
5855
type = ("{0}/{1}" -f $dscObject.ModuleName, $dscObject.ResourceName)
@@ -61,24 +58,20 @@ function Build-DscConfigDocument
6158

6259
$properties = [ordered]@{}
6360

64-
foreach ($dscObjectProperty in $dscObject.GetEnumerator())
65-
{
66-
if ($dscObjectProperty.Key -notin @('ResourceInstanceName', 'ResourceName', 'ModuleName', 'DependsOn', 'ConfigurationName', 'Type'))
67-
{
61+
foreach ($dscObjectProperty in $dscObject.GetEnumerator()) {
62+
if ($dscObjectProperty.Key -notin @('ResourceInstanceName', 'ResourceName', 'ModuleName', 'DependsOn', 'ConfigurationName', 'Type')) {
6863
$properties.Add($dscObjectProperty.Key, $dscObjectProperty.Value)
6964
}
7065
}
7166

7267
# add properties
7368
$resource.properties = $properties
7469

75-
if ($dscObject.ContainsKey('DependsOn') -and $dscObject.DependsOn)
76-
{
70+
if ($dscObject.ContainsKey('DependsOn') -and $dscObject.DependsOn) {
7771
$dependsOnKeys = $dscObject.DependsOn.Split("]").Replace("[", "")
7872

7973
$previousGroupHash = $dscObjects | Where-Object { $_.ResourceName -eq $dependsOnKeys[0] -and $_.ResourceInstanceName -eq $dependsOnKeys[1] }
80-
if ($previousGroupHash)
81-
{
74+
if ($previousGroupHash) {
8275
$dependsOnString = "[resourceId('$("{0}/{1}" -f $previousGroupHash.ModuleName, $previousGroupHash.ResourceName)','$($previousGroupHash.ResourceInstanceName)')]"
8376

8477
# add it to the object
@@ -94,8 +87,7 @@ function Build-DscConfigDocument
9487
return $configurationDocument
9588
}
9689

97-
function ConvertTo-DscObject
98-
{
90+
function ConvertTo-DscObject {
9991
[CmdletBinding()]
10092
param
10193
(
@@ -110,33 +102,26 @@ function ConvertTo-DscObject
110102

111103
# Remove the module version information.
112104
$start = $Content.ToLower().IndexOf('import-dscresource')
113-
if ($start -ge 0)
114-
{
105+
if ($start -ge 0) {
115106
$end = $Content.IndexOf("`n", $start)
116-
if ($end -gt $start)
117-
{
107+
if ($end -gt $start) {
118108
$start = $Content.ToLower().IndexOf("-moduleversion", $start)
119-
if ($start -ge 0 -and $start -lt $end)
120-
{
109+
if ($start -ge 0 -and $start -lt $end) {
121110
$Content = $Content.Remove($start, $end - $start)
122111
}
123112
}
124113
}
125114

126115
# Rename the configuration node to ensure a valid name is used.
127116
$start = $Content.ToLower().IndexOf("`nconfiguration")
128-
if ($start -lt 0)
129-
{
117+
if ($start -lt 0) {
130118
$start = $Content.ToLower().IndexOf(' configuration ')
131119
}
132-
if ($start -ge 0)
133-
{
120+
if ($start -ge 0) {
134121
$end = $Content.IndexOf("`n", $start)
135-
if ($end -gt $start)
136-
{
122+
if ($end -gt $start) {
137123
$start = $Content.ToLower().IndexOf(' ', $start + 1)
138-
if ($start -ge 0 -and $start -lt $end)
139-
{
124+
if ($start -ge 0 -and $start -lt $end) {
140125
$Content = $Content.Remove($start, $end - $start)
141126
$Content = $Content.Insert($start, " TempDSCParserConfiguration")
142127
}
@@ -151,29 +136,21 @@ function ConvertTo-DscObject
151136
# Retrieve information about the DSC Modules imported in the config
152137
# and get the list of their associated resources.
153138
$ModulesToLoad = @()
154-
foreach ($statement in $config.body.ScriptBlock.EndBlock.Statements)
155-
{
139+
foreach ($statement in $config.body.ScriptBlock.EndBlock.Statements) {
156140
if ($null -ne $statement.CommandElements -and $null -ne $statement.CommandElements[0].Value -and `
157-
$statement.CommandElements[0].Value -eq 'Import-DSCResource')
158-
{
141+
$statement.CommandElements[0].Value -eq 'Import-DSCResource') {
159142
$currentModule = @{}
160-
for ($i = 0; $i -le $statement.CommandElements.Count; $i++)
161-
{
143+
for ($i = 0; $i -le $statement.CommandElements.Count; $i++) {
162144
if ($statement.CommandElements[$i].ParameterName -eq 'ModuleName' -and `
163-
($i + 1) -lt $statement.CommandElements.Count)
164-
{
145+
($i + 1) -lt $statement.CommandElements.Count) {
165146
$moduleName = $statement.CommandElements[$i + 1].Value
166147
$currentModule.Add('ModuleName', $moduleName)
167-
}
168-
elseif ($statement.CommandElements[$i].ParameterName -eq 'Module' -and `
169-
($i + 1) -lt $statement.CommandElements.Count)
170-
{
148+
} elseif ($statement.CommandElements[$i].ParameterName -eq 'Module' -and `
149+
($i + 1) -lt $statement.CommandElements.Count) {
171150
$moduleName = $statement.CommandElements[$i + 1].Value
172151
$currentModule.Add('ModuleName', $moduleName)
173-
}
174-
elseif ($statement.CommandElements[$i].ParameterName -eq 'ModuleVersion' -and `
175-
($i + 1) -lt $statement.CommandElements.Count)
176-
{
152+
} elseif ($statement.CommandElements[$i].ParameterName -eq 'ModuleVersion' -and `
153+
($i + 1) -lt $statement.CommandElements.Count) {
177154
$moduleVersion = $statement.CommandElements[$i + 1].Value
178155
$currentModule.Add('ModuleVersion', $moduleVersion)
179156
}
@@ -182,36 +159,27 @@ function ConvertTo-DscObject
182159
}
183160
}
184161
$DSCResources = @()
185-
foreach ($moduleToLoad in $ModulesToLoad)
186-
{
162+
foreach ($moduleToLoad in $ModulesToLoad) {
187163
$loadedModuleTest = Get-Module -Name $moduleToLoad.ModuleName -ListAvailable | Where-Object -FilterScript { $_.Version -eq $moduleToLoad.ModuleVersion }
188164

189-
if ($null -eq $loadedModuleTest -and -not [System.String]::IsNullOrEmpty($moduleToLoad.ModuleVersion))
190-
{
165+
if ($null -eq $loadedModuleTest -and -not [System.String]::IsNullOrEmpty($moduleToLoad.ModuleVersion)) {
191166
"Module {$($moduleToLoad.ModuleName)} version {$($moduleToLoad.ModuleVersion)} specified in the configuration isn't installed on the machine/agent. Install it by running: Install-Module -Name '$($moduleToLoad.ModuleName)' -RequiredVersion '$($moduleToLoad.ModuleVersion)'" | Write-DscTrace -Operation Error
192167
exit 1
193-
}
194-
else
195-
{
196-
if ($Script:IsPowerShellCore)
197-
{
168+
} else {
169+
if ($Script:IsPowerShellCore) {
198170
$currentResources = Get-PwshDscResource -Module $moduleToLoad.ModuleName
199-
}
200-
else
201-
{
171+
} else {
202172
$currentResources = Get-DSCResource -Module $moduleToLoad.ModuleName
203173
}
204174

205-
if (-not [System.String]::IsNullOrEmpty($moduleToLoad.ModuleVersion))
206-
{
175+
if (-not [System.String]::IsNullOrEmpty($moduleToLoad.ModuleVersion)) {
207176
$currentResources = $currentResources | Where-Object -FilterScript { $_.Version -eq $moduleToLoad.ModuleVersion }
208177
}
209178
$DSCResources += $currentResources
210179
}
211180
}
212181

213-
if ($DSCResources.Count -eq 0)
214-
{
182+
if ($DSCResources.Count -eq 0) {
215183
"No DSC resources found in the imported modules." | Write-DscTrace -Operation Error
216184
exit 1
217185
}
@@ -220,21 +188,17 @@ function ConvertTo-DscObject
220188
# Body.ScriptBlock is the part after "Configuration <InstanceName> {"
221189
# EndBlock is the actual code within that Configuration block
222190
# Find the first DynamicKeywordStatement that has a word "Node" in it, find all "NamedBlockAst" elements, these are the DSC resource definitions
223-
try
224-
{
191+
try {
225192
$resourceInstances = $Config.Body.ScriptBlock.EndBlock.Statements.Find({ $Args[0].GetType().Name -eq 'DynamicKeywordStatementAst' -and $Args[0].CommandElements[0].StringConstantType -eq 'BareWord' -and $Args[0].CommandElements[0].Value -eq 'Node' }, $False).commandElements[2].ScriptBlock.Find({ $Args[0].GetType().Name -eq 'NamedBlockAst' }, $False).Statements
226-
}
227-
catch
228-
{
193+
} catch {
229194
$resourceInstances = $Config.Body.ScriptBlock.EndBlock.Statements | Where-Object -FilterScript { $null -ne $_.CommandElements -and $_.CommandElements[0].Value -ne 'Import-DscResource' }
230195
}
231196

232197
# Get the name of the configuration.
233198
$configurationName = $Config.InstanceName.Value
234199

235200
$totalCount = 1
236-
foreach ($resource in $resourceInstances)
237-
{
201+
foreach ($resource in $resourceInstances) {
238202
$currentResourceInfo = @{}
239203

240204
# CommandElements
@@ -257,61 +221,41 @@ function ConvertTo-DscObject
257221
$currentResource = $DSCResources | Where-Object -FilterScript { $_.Name -eq $resourceType }
258222

259223
# Loop through all the key/pair value
260-
foreach ($keyValuePair in $resource.CommandElements[2].KeyValuePairs)
261-
{
224+
foreach ($keyValuePair in $resource.CommandElements[2].KeyValuePairs) {
262225
$isVariable = $false
263226
$key = $keyValuePair.Item1.Value
264227

265-
if ($null -ne $keyValuePair.Item2.PipelineElements)
266-
{
267-
if ($null -eq $keyValuePair.Item2.PipelineElements.Expression.Value)
268-
{
269-
if ($null -ne $keyValuePair.Item2.PipelineElements.Expression)
270-
{
271-
if ($keyValuePair.Item2.PipelineElements.Expression.StaticType.Name -eq 'Object[]')
272-
{
228+
if ($null -ne $keyValuePair.Item2.PipelineElements) {
229+
if ($null -eq $keyValuePair.Item2.PipelineElements.Expression.Value) {
230+
if ($null -ne $keyValuePair.Item2.PipelineElements.Expression) {
231+
if ($keyValuePair.Item2.PipelineElements.Expression.StaticType.Name -eq 'Object[]') {
273232
$value = $keyValuePair.Item2.PipelineElements.Expression.SubExpression
274233
$newValue = @()
275-
foreach ($expression in $value.Statements.PipelineElements.Expression)
276-
{
277-
if ($null -ne $expression.Elements)
278-
{
279-
foreach ($element in $expression.Elements)
280-
{
281-
if ($null -ne $element.VariablePath)
282-
{
234+
foreach ($expression in $value.Statements.PipelineElements.Expression) {
235+
if ($null -ne $expression.Elements) {
236+
foreach ($element in $expression.Elements) {
237+
if ($null -ne $element.VariablePath) {
283238
$newValue += "`$" + $element.VariablePath.ToString()
284-
}
285-
elseif ($null -ne $element.Value)
286-
{
239+
} elseif ($null -ne $element.Value) {
287240
$newValue += $element.Value
288241
}
289242
}
290-
}
291-
else
292-
{
243+
} else {
293244
$newValue += $expression.Value
294245
}
295246
}
296247
$value = $newValue
297-
}
298-
else
299-
{
248+
} else {
300249
$value = $keyValuePair.Item2.PipelineElements.Expression.ToString()
301250
}
302-
}
303-
else
304-
{
251+
} else {
305252
$value = $keyValuePair.Item2.PipelineElements.Parent.ToString()
306253
}
307254

308-
if ($value.GetType().Name -eq 'String' -and $value.StartsWith('$'))
309-
{
255+
if ($value.GetType().Name -eq 'String' -and $value.StartsWith('$')) {
310256
$isVariable = $true
311257
}
312-
}
313-
else
314-
{
258+
} else {
315259
$value = $keyValuePair.Item2.PipelineElements.Expression.Value
316260
}
317261
}
@@ -323,19 +267,16 @@ function ConvertTo-DscObject
323267
# If the value type is null, then the parameter doesn't exist
324268
# in the resource's schema and we throw a warning
325269
$propertyFound = $true
326-
if ($null -eq $valueType)
327-
{
270+
if ($null -eq $valueType) {
328271
$propertyFound = $false
329272
}
330273

331-
if ($propertyFound)
332-
{
274+
if ($propertyFound) {
333275
# If the current property is not a CIMInstance
334276
if (-not $valueType.StartsWith('[MSFT_') -and `
335277
$valueType -ne '[string]' -and `
336278
$valueType -ne '[string[]]' -and `
337-
-not $isVariable)
338-
{
279+
-not $isVariable) {
339280
# Try to parse the value based on the retrieved type.
340281
$scriptBlock = @"
341282
`$typeStaticMethods = $valueType | gm -static
@@ -345,44 +286,29 @@ function ConvertTo-DscObject
345286
}
346287
"@
347288
Invoke-Expression -Command $scriptBlock | Out-Null
348-
}
349-
elseif ($valueType -eq '[String]' -or $isVariable)
350-
{
351-
if ($isVariable -and [Boolean]::TryParse($value.TrimStart('$'), [ref][Boolean]))
352-
{
353-
if ($value -eq "`$true")
354-
{
289+
} elseif ($valueType -eq '[String]' -or $isVariable) {
290+
if ($isVariable -and [Boolean]::TryParse($value.TrimStart('$'), [ref][Boolean])) {
291+
if ($value -eq "`$true") {
355292
$value = $true
356-
}
357-
else
358-
{
293+
} else {
359294
$value = $false
360295
}
361-
}
362-
else
363-
{
296+
} else {
364297
$value = $value
365298
}
366-
}
367-
elseif ($valueType -eq '[string[]]')
368-
{
299+
} elseif ($valueType -eq '[string[]]') {
369300
# If the property is an array but there's only one value
370301
# specified as a string (not specifying the @()) then
371302
# we need to create the array.
372-
if ($value.GetType().Name -eq 'String' -and -not $value.StartsWith('@('))
373-
{
303+
if ($value.GetType().Name -eq 'String' -and -not $value.StartsWith('@(')) {
374304
$value = @($value)
375305
}
376-
}
377-
else
378-
{
306+
} else {
379307
$isArray = $false
380-
if ($keyValuePair.Item2.ToString().StartsWith('@('))
381-
{
308+
if ($keyValuePair.Item2.ToString().StartsWith('@(')) {
382309
$isArray = $true
383310
}
384-
if ($isArray)
385-
{
311+
if ($isArray) {
386312
$value = @($value)
387313
}
388314
}

0 commit comments

Comments
 (0)