DscResources/MSFT_WindowsOptionalFeature/MSFT_WindowsOptionalFeature.psm1

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
# PSSA global rule suppression is allowed here because $global:DSCMachineStatus must be set
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')]
param ()

$errorActionPreference = 'Stop'
Set-StrictMode -Version 'Latest'

Import-Module -Name (Join-Path -Path (Split-Path -Path $PSScriptRoot -Parent) `
                               -ChildPath 'CommonResourceHelper.psm1')
$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_WindowsOptionalFeature'

<#
    .SYNOPSIS
        Retrieves the state of a Windows optional feature resource.
 
    .PARAMETER Name
        The name of the Windows optional feature resource to retrieve.
#>

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $Name
    )

    Write-Verbose -Message ($LocalizedData.GetTargetResourceStartMessage -f $Name)

    Assert-ResourcePrerequisitesValid

    $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -FeatureName $Name -Online
    
    <#
        $windowsOptionalFeatureProperties and this section of code are needed because an error will be thrown if a property
        is not found in WMF 4 instead of returning null.
    #>
 
    $windowsOptionalFeatureProperties = @{}
    $propertiesNeeded = @( 'LogPath', 'State', 'CustomProperties', 'FeatureName', 'LogLevel', 'Description', 'DisplayName' )

    foreach ($property in $propertiesNeeded)
    {
        try
        {
            $windowsOptionalFeatureProperties[$property] = $windowsOptionalFeature.$property
        }
        catch
        {
            $windowsOptionalFeatureProperties[$property] = $null
        }
    }

    $windowsOptionalFeatureResource = @{
        LogPath = $windowsOptionalFeatureProperties.LogPath
        Ensure = Convert-FeatureStateToEnsure -State $windowsOptionalFeatureProperties.State
        CustomProperties =
            Convert-CustomPropertyArrayToStringArray -CustomProperties $windowsOptionalFeatureProperties.CustomProperties
        Name = $windowsOptionalFeatureProperties.FeatureName
        LogLevel = $windowsOptionalFeatureProperties.LogLevel
        Description = $windowsOptionalFeatureProperties.Description
        DisplayName = $windowsOptionalFeatureProperties.DisplayName
    }

    Write-Verbose -Message ($script:localizedData.GetTargetResourceEndMessage -f $Name)

    return $windowsOptionalFeatureResource
}

<#
    .SYNOPSIS
        Enables or disables a Windows optional feature
 
    .PARAMETER Name
        The name of the feature to enable or disable.
 
    .PARAMETER Ensure
        Specifies whether the feature should be enabled or disabled.
        To enable the feature, set this property to Present.
        To disable the feature, set the property to Absent.
 
    .PARAMETER RemoveFilesOnDisable
        Specifies that all files associated with the feature should be removed if the feature is
        being disabled.
 
    .PARAMETER NoWindowsUpdateCheck
        Specifies whether or not DISM contacts Windows Update (WU) when searching for the source
        files to enable the feature.
        If $true, DISM will not contact WU.
 
    .PARAMETER LogPath
        The path to the log file to log this operation.
        There is no default value, but if not set, the log will appear at
        %WINDIR%\Logs\Dism\dism.log.
 
    .PARAMETER LogLevel
        The maximum output level to show in the log.
        Accepted values are: "ErrorsOnly" (only errors are logged), "ErrorsAndWarning" (errors and
        warnings are logged), and "ErrorsAndWarningAndInformation" (errors, warnings, and debug
        information are logged).
#>

function Set-TargetResource
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $Name,

        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [String]
        $Ensure = 'Present',

        [Parameter()]
        [Boolean]
        $RemoveFilesOnDisable,

        [Parameter()]
        [Boolean]
        $NoWindowsUpdateCheck,

        [Parameter()]
        [String]
        $LogPath,

        [Parameter()]
        [ValidateSet('ErrorsOnly', 'ErrorsAndWarning', 'ErrorsAndWarningAndInformation')]
        [String]
        $LogLevel = 'ErrorsAndWarningAndInformation'
    )

    Write-Verbose -Message ($script:localizedData.SetTargetResourceStartMessage -f $Name)

    Assert-ResourcePrerequisitesValid

    $dismLogLevel = switch ($LogLevel)
    {
        'ErrorsOnly' {  'Errors'; break }
        'ErrorsAndWarning' { 'Warnings'; break }
        'ErrorsAndWarningAndInformation' { 'WarningsInfo'; break }
    }

    # Construct splatting hashtable for DISM cmdlets
    $dismCmdletParameters = @{
        FeatureName = $Name
        Online = $true
        LogLevel = $dismLogLevel
        NoRestart = $true
    }

    if ($PSBoundParameters.ContainsKey('LogPath'))
    {
        $dismCmdletParameters['LogPath'] = $LogPath
    }

    if ($Ensure -eq 'Present')
    {
        if ($PSCmdlet.ShouldProcess($Name, $script:localizedData.ShouldProcessEnableFeature))
        {
            if ($NoWindowsUpdateCheck)
            {
                $dismCmdletParameters['LimitAccess'] =  $true
            }

            $windowsOptionalFeature = Dism\Enable-WindowsOptionalFeature @dismCmdletParameters
        }

        Write-Verbose -Message ($script:localizedData.FeatureInstalled -f $Name)
    }
    else
    {
        if ($PSCmdlet.ShouldProcess($Name, $script:localizedData.ShouldProcessDisableFeature))
        {
            if ($RemoveFilesOnDisable)
            {
                $dismCmdletParameters['Remove'] = $true
            }

            $windowsOptionalFeature = Dism\Disable-WindowsOptionalFeature @dismCmdletParameters
        }

        Write-Verbose -Message ($script:localizedData.FeatureUninstalled -f $Name)
    }

    <#
        $restartNeeded and this section of code are needed because an error will be thrown if the
        RestartNeeded property is not found in WMF 4.
    #>
 
    try
    {
        $restartNeeded = $windowsOptionalFeature.RestartNeeded
    }
    catch
    {
        $restartNeeded = $false
    }

    # Indicate we need a restart if needed
    if ($restartNeeded)
    {
        Write-Verbose -Message $script:localizedData.RestartNeeded
        $global:DSCMachineStatus = 1
    }

    Write-Verbose -Message ($script:localizedData.SetTargetResourceEndMessage -f $Name)
}

<#
    .SYNOPSIS
        Tests if a Windows optional feature is in the specified state.
 
    .PARAMETER Name
        The name of the feature to test the state of.
 
    .PARAMETER Ensure
        Specifies whether the feature should be enabled or disabled.
        To test if the feature is enabled, set this property to Present.
        To test if the feature is disabled, set this property to Absent.
 
    .PARAMETER RemoveFilesOnDisable
        Not used in Test-TargetResource.
 
    .PARAMETER NoWindowsUpdateCheck
        Not used in Test-TargetResource.
 
    .PARAMETER LogPath
        Not used in Test-TargetResource.
 
    .PARAMETER LogLevel
        Not used in Test-TargetResource.
#>

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $Name,

        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [String]
        $Ensure = 'Present',

        [Parameter()]
        [Boolean]
        $RemoveFilesOnDisable,

        [Parameter()]
        [Boolean]
        $NoWindowsUpdateCheck,

        [Parameter()]
        [String]
        $LogPath,

        [Parameter()]
        [ValidateSet('ErrorsOnly', 'ErrorsAndWarning', 'ErrorsAndWarningAndInformation')]
        [String]
        $LogLevel = 'ErrorsAndWarningAndInformation'
    )

    Write-Verbose -Message ($script:localizedData.TestTargetResourceStartMessage -f $Name)

    Assert-ResourcePrerequisitesValid

    $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -FeatureName $Name -Online
    
    $featureIsInDesiredState = $false

    if ($null -eq $windowsOptionalFeature -or $windowsOptionalFeature.State -eq 'Disabled')
    {
        $featureIsInDesiredState = $Ensure -eq 'Absent'
    }
    elseif ($windowsOptionalFeature.State -eq 'Enabled')
    {
        $featureIsInDesiredState = $Ensure -eq 'Present'
    }
    
    Write-Verbose -Message ($script:localizedData.TestTargetResourceEndMessage -f $Name)
    
    return $featureIsInDesiredState
}

<#
    .SYNOPSIS
        Converts a list of CustomProperty objects into an array of Strings.
 
    .PARAMETER CustomProperties
        The list of CustomProperty objects to be converted.
        Each CustomProperty object should have Name, Value, and Path properties.
#>

function Convert-CustomPropertyArrayToStringArray
{
    [CmdletBinding()]
    [OutputType([String[]])]
    param
    (
        [Parameter()]
        [PSCustomObject[]]
        $CustomProperties
    )

    $propertiesAsStrings = [String[]] @()

    foreach ($customProperty in $CustomProperties)
    {
        if ($null -ne $customProperty)
        {
            $propertiesAsStrings += "Name = $($customProperty.Name), Value = $($customProperty.Value), Path = $($customProperty.Path)"
        }
    }

    return $propertiesAsStrings
}

<#
    .SYNOPSIS
        Converts the string state returned by the DISM Get-WindowsOptionalFeature cmdlet to Present or Absent.
 
    .PARAMETER State
        The state to be converted to either Present or Absent.
        Should be either Enabled or Disabled.
#>

function Convert-FeatureStateToEnsure
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $State
    )

    if ($State -eq 'Disabled')
    {
        return 'Absent'
    }
    elseif ($State -eq 'Enabled')
    {
        return 'Present'
    }
    else
    {
        Write-Warning ($script:localizedData.CouldNotConvertFeatureState -f $State)
        return $State
    }
}

<#
    .SYNOPSIS
        Throws errors if the prerequisites for using WindowsOptionalFeature are not met on the
        target machine.
 
        Current prerequisites are:
            - Must be running either a Windows client, at least Windows Server 2012, or Nano Server
            - Must be running as an administrator
            - The DISM PowerShell module must be available for import
#>

function Assert-ResourcePrerequisitesValid
{
    [CmdletBinding()]
    param ()

    Write-Verbose -Message $script:localizedData.ValidatingPrerequisites

    # Check that we're running on Server 2012 (or later) or on a client SKU
    $operatingSystem = Get-CimInstance -ClassName 'Win32_OperatingSystem'

    if (($operatingSystem.ProductType -eq 2) -and ([System.Int32] $operatingSystem.BuildNumber -lt 9600))
    {
        New-InvalidOperationException -Message $script:localizedData.NotSupportedSku
    }

    # Check that we are running as an administrator
    $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $windowsPrincipal = New-Object -TypeName 'System.Security.Principal.WindowsPrincipal' -ArgumentList @( $windowsIdentity )
    
    $adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
    if (-not $windowsPrincipal.IsInRole($adminRole))
    {
        New-InvalidOperationException -Message $script:localizedData.ElevationRequired
    }

    # Check that Dism PowerShell module is available
    Import-Module -Name 'Dism' -ErrorVariable 'errorsFromDismImport' -ErrorAction 'SilentlyContinue' -Force

    if ($errorsFromDismImport.Count -gt 0)
    {
        New-InvalidOperationException -Message $script:localizedData.DismNotAvailable
    }
}

Export-ModuleMember -Function *-TargetResource