DSCResources/Grani_PendingReboot/Grani_PendingReboot.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
#region Initialize

function Initialize
{
    $script:TempPath = "$env:LOCALAPPDATA\Temp\{0}" -f [Guid]::NewGuid().ToString()
    $script:pendingSec = 20

    # Enum for Ensure
    Add-Type -TypeDefinition @"
        public enum EnsureType
        {
            Present,
            Absent
        }
"@
 -ErrorAction SilentlyContinue

    # Enum for RebootTrigger
    Add-Type -TypeDefinition @"
        public enum RebootTriggerType
        {
            ComponentBasedServicing,
            WindowsUpdate,
            PendingFileRename,
            PendingComputerRename,
            CcmClientSDK
        }
"@
 -ErrorAction SilentlyContinue
}

Initialize

#endregion

#region Message Definition

$verboseMessages = Data {
    ConvertFrom-StringData -StringData @"
        SetLCMStatus = Setting the DSCMachineStatus global variable to 1.
        WaitTimeSecDetect = WaitTimeSec detected. Waiting {0}sec before enable reboot flag.
        PendingRebootUntilDSCReboot = Pending Reboot for {0}sec for when RebootIfNeeded is $true. Even $false will reboot until time past.
"@

}

$debugMessages = Data {
    ConvertFrom-StringData -StringData @"
        ChangeLCMRebootNodeIfNeeded = Changing Local Configuration Manager RebootNodeIfNeeded status from '{0}' to '{1}'
        PendingRebootDetect = A pending reboot was found for : {0}.
        SCCMCanNotQueryException = Unable to query CCM_ClientUtilities: {0}
        SkipTriggerChecking = {0}Trigger detect $false. Skipping Trigger check.
"@

}

$errorMessages = Data {
    ConvertFrom-StringData -StringData @"
"@

}

#endregion

#region *-TargetResource

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

        [parameter(Mandatory = $false)]
        [System.UInt32]$WaitTimeSec = 0,

        [parameter(Mandatory = $false)]
        [System.Boolean]$Force = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$WhatIf = $false,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerComponentBasedServicing = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerWindowsUpdate = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerPendingFileRename = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerPendingComputerRename = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerCcmClientSDK = $true
    )

    # return hash
    $returnValue = @{
        Name = $Name
        WaitTimeSec = $WaitTimeSec
        Force = $Force
        WhatIf = $WhatIf
        TriggerComponentBasedServicing = $TriggerComponentBasedServicing
        TriggerWindowsUpdate = $TriggerWindowsUpdate
        TriggerPendingFileRename = $TriggerPendingFileRename
        TriggerPendingComputerRename = $TriggerPendingComputerRename
        TriggerCcmClientSDK = $TriggerCcmClientSDK
    }

    # initialize
    $scriptBlocks = @()

    # Windows Component Reboot Check
    if ($TriggerComponentBasedServicing)
    {
        $scriptBlocks += @{
            [RebootTriggerType]::ComponentBasedServicing.ToString() = {
                (Split-Path (Get-ChildItem 'registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\').Name -Leaf) -contains "RebootPending"
            }
        }
    }
    else
    {
        Write-Debug ($debugMessages.SkipTriggerChecking -f [RebootTriggerType]::ComponentBasedServicing.ToString())
        $returnValue.([RebootTriggerType]::ComponentBasedServicing.ToString()) = $false
    }

    # Windows Update Reboot Check
    if ($TriggerWindowsUpdate)
    {
        $scriptBlocks += @{
            [RebootTriggerType]::WindowsUpdate.ToString() = {
                (Split-Path (Get-ChildItem 'registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\').Name -Leaf) -contains "RebootRequired"
            }
        }
    }
    else
    {
        Write-Debug ($debugMessages.SkipTriggerChecking -f [RebootTriggerType]::WindowsUpdate.ToString())
        $returnValue.([RebootTriggerType]::WindowsUpdate.ToString()) = $false
    }

    # PendingFileRename
    if ($TriggerPendingFileRename)
    {
        $scriptBlocks += @{
            [RebootTriggerType]::PendingFileRename.ToString() = {
                (Get-ItemProperty 'registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\').PendingFileRenameOperations.Length -gt 0
            }
        }
    }
    else
    {
        Write-Debug ($debugMessages.SkipTriggerChecking -f [RebootTriggerType]::PendingFileRename.ToString())
        $returnValue.([RebootTriggerType]::PendingFileRename.ToString()) = $false
    }

    # Computer Name Reboot Check
    if ($TriggerPendingComputerRename)
    {
        $scriptBlocks += @{
            [RebootTriggerType]::PendingComputerRename.ToString() = {
                $ActiveComputerName = (Get-ItemProperty 'registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName').ComputerName
                $PendingComputerName = (Get-ItemProperty 'registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName').ComputerName
                $ActiveComputerName -ne $PendingComputerName
            }
        }
    }
    else
    {
        Write-Debug ($debugMessages.SkipTriggerChecking -f [RebootTriggerType]::PendingComputerRename.ToString())
        $returnValue.([RebootTriggerType]::PendingComputerRename.ToString()) = $false
    }

    # System Center Reboot Check
    if ($TriggerCcmClientSDK)
    {
        $scriptBlocks += @{
            [RebootTriggerType]::CcmClientSDK.ToString() = {
                try
                {
                    $CCMSplat = @{
                        NameSpace='ROOT\ccm\ClientSDK'
                        Class='CCM_ClientUtilities'
                        Name='DetermineIfRebootPending'
                        ErrorAction='Stop'
                    }
                    $CCMClientSDK = Invoke-WmiMethod @CCMSplat
                    ($CCMClientSDK.ReturnValue -eq 0) -and ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending)
                }
                catch
                {
                    $false
                    Write-Debug ($debugMessages.SCCMCanNotQueryException -f $_)
                }
            }
        }
    }
    else
    {
        Write-Debug ($debugMessages.SkipTriggerChecking -f [RebootTriggerType]::CcmClientSDK.ToString())
        $returnValue.([RebootTriggerType]::CcmClientSDK.ToString()) = $false
    }

    # execute Each Parameter
    $ensure = [EnsureType]::Present
    if (($scriptBlocks | measure).Count -ne 0)
    {
        foreach ($script in $scriptBlocks.Keys)
        {
            $returnValue.$script = & $scriptBlocks."$script"
            If ($returnValue.$script)
            {
                Write-Debug ($debugMessages.PendingRebootDetect -f $script)
                $Ensure = [EnsureType]::Absent
            }
        }
    }
   
    # ensure
    $returnValue.Ensure = $ensure

    # return
    return $returnValue
}


function Set-TargetResource
{
    [OutputType([Void])]
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Name,

        [parameter(Mandatory = $false)]
        [System.UInt32]$WaitTimeSec = 0,

        [parameter(Mandatory = $false)]
        [System.Boolean]$Force = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$WhatIf = $false,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerComponentBasedServicing = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerWindowsUpdate = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerPendingFileRename = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerPendingComputerRename = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerCcmClientSDK = $true
    )

    # Sleep for WaitTimeSec
    SleepWaitTimeSec -WaitTimeSec $WaitTimeSec

    # Set DSCMachineStatus
    Write-Verbose $verboseMessages.SetLCMStatus
    $global:DSCMachineStatus = 1

    # Manual Reboot
    ManualReboot -Force $Force -WhatIf $WhatIf
}


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

        [parameter(Mandatory = $false)]
        [System.UInt32]$WaitTimeSec = 0,

        [parameter(Mandatory = $false)]
        [System.Boolean]$Force = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$WhatIf = $false,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerComponentBasedServicing = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerWindowsUpdate = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerPendingFileRename = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerPendingComputerRename = $true,

        [parameter(Mandatory = $false)]
        [System.Boolean]$TriggerCcmClientSDK = $true
    )

    return (Get-TargetResource -Name $Name -WaitTime $WaitTime -Force $Force -WhatIf $WhatIf -TriggerComponentBasedServicing $TriggerComponentBasedServicing -TriggerWindowsUpdate $TriggerWindowsUpdate -TriggerPendingFileRename $TriggerPendingFileRename -TriggerPendingComputerRename $TriggerPendingComputerRename -TriggerCcmClientSDK $TriggerCcmClientSDK).Ensure -eq [EnsureType]::Present.ToString()
}

#endregion

#region Set Helper

function SleepWaitTimeSec ([Uint32]$WaitTimeSec)
{
    if ($WaitTimeSec -ne 0)
    {
        Write-Verbose ($verboseMessages.WaitTimeSecDetect -f $WaitTimeSec)
        [System.Threading.Thread]::Sleep([TimeSpan]::FromSeconds($WaitTimeSec))
    }
}

function ManualReboot ($Force, $WhatIf)
{
    if (-not $WhatIf)
    {
        Write-Verbose ($verboseMessages.PendingRebootUntilDSCReboot -f $script:pendingSec)
        [System.Threading.Thread]::Sleep([TimeSpan]::FromSeconds($script:pendingSec))
    }
    Restart-Computer -Force:$Force -WhatIf:$WhatIf
}

#endregion

Export-ModuleMember -Function *-TargetResource