DSCResources/MSFT_xWindowsOptionalFeature/MSFT_xWindowsOptionalFeature.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
# This PS module contains functions for Desired State Configuration Windows Optional Feature provider. It enables configuring optional features on Windows Client SKUs.

# Fallback message strings in en-US
DATA localizedData
{
    # culture = "en-US"
    ConvertFrom-StringData @'
        DismNotAvailable = PowerShell module Dism could not be imported.
        NotSupportedSku = This Resource is only available for Windows Client or Server 2012 (or later).
        ElevationRequired = This Resource requires to be run as an Administrator.
        ValidatingPrerequisites = Validating prerequisites...
        CouldNotCovertFeatureState = Could not convert feature state '{0}' into Absent/Present.
        EnsureNotSupported = The value '{0}' for property Ensure is not supported.
        RestartNeeded = Target machine needs to be restarted.
        GetTargetResourceStartMessage = Begin executing Get functionality on the {0} feature.
        GetTargetResourceEndMessage = End executing Get functionality on the {0} feature.
        SetTargetResourceStartMessage = Begin executing Set functionality on the {0} feature.
        SetTargetResourceEndMessage = End executing Set functionality on the {0} feature.
        TestTargetResourceStartMessage = Begin executing Test functionality on the {0} feature.
        TestTargetResourceEndMessage = End executing Test functionality on the {0} feature.
        FeatureInstalled = Installed feature {0}.
        FeatureUninstalled = Uninstalled feature {0}.
'@

}
Import-Module Dism -Force -ErrorAction SilentlyContinue

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]
        $Name
    )

    Write-Debug ($LocalizedData.GetTargetResourceStartMessage -f $Name)

    ValidatePrerequisites

    $result = Dism\Get-WindowsOptionalFeature -FeatureName $Name -Online

    $returnValue = @{
        LogPath = $result.LogPath
        Ensure = ConvertStateToEnsure $result.State
        CustomProperties = SerializeCustomProperties $result.CustomProperties
        Name = $result.FeatureName
        LogLevel = $result.LogLevel
        Description = $result.Description
        DisplayName = $result.DisplayName
    }

    $returnValue

    Write-Debug ($LocalizedData.GetTargetResourceEndMessage -f $Name)
}

# Serializes a list of CustomProperty objects into [System.String[]]
function SerializeCustomProperties
{
    param
    (
        $CustomProperties
    )

    $CustomProperties | ? {$_ -ne $null} | % { "Name = $($_.Name), Value = $($_.Value), Path = $($_.Path)" }
}

# Converts state returned by Dism Get-WindowsOptionalFeature cmdlet to Present/Absent
function ConvertStateToEnsure
{
    param
    (
        $State
    )

    if ($state -eq 'Disabled')
    {
        'Absent'
    }
    elseif ($state -eq 'Enabled')
    {
        'Present'
    }
    else
    {
        Write-Warning ($LocalizedData.CouldNotCovertFeatureState -f $state)
        $state
    }
}


function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [System.String[]]
        $Source,

        [System.Boolean]
        $RemoveFilesOnDisable,

        [System.String]
        $LogPath,

        [ValidateSet("Present","Absent")]
        [System.String]
        $Ensure = "Present",

        [System.Boolean]
        $NoWindowsUpdateCheck,

        [parameter(Mandatory = $true)]
        [System.String]
        $Name,

        [ValidateSet("ErrorsOnly","ErrorsAndWarning","ErrorsAndWarningAndInformation")]
        [System.String]
        $LogLevel
    )

    Write-Debug ($LocalizedData.SetTargetResourceStartMessage -f $Name)

    ValidatePrerequisites

    switch ($LogLevel)
    {
        'ErrorsOnly' { $DismLogLevel = 'Errors' }
        'ErrorsAndWarning' { $DismLogLevel = 'Warnings' }
        'ErrorsAndWarningAndInformation' { $DismLogLevel = 'WarningsInfo' }
        '' { $DismLogLevel = 'WarningsInfo' }
    }

    # construct parameters for Dism cmdlets
    $PSBoundParameters.Remove('Name') > $null
    $PSBoundParameters.Remove('Ensure') > $null
    if ($PSBoundParameters.ContainsKey('RemoveFilesOnDisable'))
    {
        $PSBoundParameters.Remove('RemoveFilesOnDisable')
    }

    if ($PSBoundParameters.ContainsKey('NoWindowsUpdateCheck'))
    {
        $PSBoundParameters.Remove('NoWindowsUpdateCheck')
    }

    if ($PSBoundParameters.ContainsKey('LogLevel'))
    {
        $PSBoundParameters.Remove('LogLevel')
    }

    if ($Ensure -eq 'Present')
    {
        if ($NoWindowsUpdateCheck)
        {
            $feature = Dism\Enable-WindowsOptionalFeature -FeatureName $Name -Online -LogLevel $DismLogLevel @PSBoundParameters -LimitAccess -NoRestart
        }
        else
        {
            $feature = Dism\Enable-WindowsOptionalFeature -FeatureName $Name -Online -LogLevel $DismLogLevel @PSBoundParameters -NoRestart
        }

        Write-Verbose ($LocalizedData.FeatureInstalled -f $Name)
    }
    elseif ($Ensure -eq 'Absent')
    {
        if ($RemoveFilesOnDisable)
        {
            $feature = Dism\Disable-WindowsOptionalFeature -FeatureName $Name -Online -LogLevel $DismLogLevel @PSBoundParameters -Remove -NoRestart
        }
        else
        {
            $feature = Dism\Disable-WindowsOptionalFeature -FeatureName $Name -Online -LogLevel $DismLogLevel @PSBoundParameters -NoRestart
        }

        Write-Verbose ($LocalizedData.FeatureUninstalled -f $Name)
    }
    else
    {
        throw ($LocalizedData.EnsureNotSupported -f $Ensure)
    }

    ## Indicate we need a restart as needed
    if ($feature.RestartNeeded)
    {
        Write-Verbose $LocalizedData.RestartNeeded
        $global:DSCMachineStatus = 1
    }

    Write-Debug ($LocalizedData.SetTargetResourceEndMessage -f $Name)
}


function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [System.String[]]
        $Source,

        [System.Boolean]
        $RemoveFilesOnDisable,

        [System.String]
        $LogPath,

        [ValidateSet("Present","Absent")]
        [System.String]
        $Ensure = "Present",

        [System.Boolean]
        $NoWindowsUpdateCheck,

        [parameter(Mandatory = $true)]
        [System.String]
        $Name,

        [ValidateSet("ErrorsOnly","ErrorsAndWarning","ErrorsAndWarningAndInformation")]
        [System.String]
        $LogLevel
    )

    Write-Debug ($LocalizedData.TestTargetResourceStartMessage -f $Name)

    ValidatePrerequisites

    $featureState = Dism\Get-WindowsOptionalFeature -FeatureName $Name -Online
    [bool] $result = $false

    if ($featureState -eq $null)
    {
        $result = $Ensure -eq 'Absent'
    }
    if (($featureState.State -eq 'Disabled' -and $Ensure -eq 'Absent')`
        -or ($featureState.State -eq 'Enabled' -and $Ensure -eq 'Present'))
    {
        $result = $true
    }
    Write-Debug ($LocalizedData.TestTargetResourceEndMessage -f $Name)
    return $result
}


# ValidatePrerequisites is a helper function used to validate if the MSFT_WindowsOptionalFeature is supported on the target machine.
function ValidatePrerequisites
{
    Write-Verbose $LocalizedData.ValidatingPrerequisites

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

    if (($os.ProductType -ne 1) -and ([System.Int32] $os.BuildNumber -lt 9600))
    {
        throw $LocalizedData.NotSupportedSku
    }

    # check that we are running elevated
    $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $windowsPrincipal = new-object System.Security.Principal.WindowsPrincipal($windowsIdentity)
    $adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator

    if (!$windowsPrincipal.IsInRole($adminRole))
    {
        throw $LocalizedData.ElevationRequired
    }

    # check that Dism PowerShell module is available
    Import-Module Dism -Force -ErrorVariable ev -ErrorAction SilentlyContinue

    if ($ev.Count -gt 0)
    {
        throw $LocalizedData.DismNotAvailable
    }
}


Export-ModuleMember -Function *-TargetResource