DSCResources/xMaintenanceWindow/xMaintenanceWindow.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
<#
.SYNOPSIS
    Returns the nth day of the month
.PARAMETER Year
    The year in which we check
.PARAMETER Month
    The number of the month in which we check
.PARAMETER Day
    The DayOfWeek object which occurrence we want
.PARAMETER Occurrence
    The n in nth day of the month
#>

function Get-DayOfMonth
{
    [CmdletBinding()]
    param
    (
        [System.Int16]
        $Year,

        [System.int16]
        $Month,

        [System.DayOfWeek]
        $Day,

        [System.int16]
        $Occurrence
    )

    $firstDayOfMonth = New-Object -TypeName System.DateTime($Year, $Month, 1)
    $firstOccurrence = $firstDayOfMonth.AddDays((7 - ([int]$firstDayOfMonth.DayOfWeek - [int]$Day)) % 7)

    return $firstOccurrence.AddDays(7 * ($Occurrence - 1))
}

<#
.SYNOPSIS
    Gets the current resource status
.PARAMETER ScheduleStart
    The start of the schedule. The property TimeOfDay is used for setting the schedule
.PARAMETER ScheduleEnd
    The end of the schedule. The property TimeOfDay is used for setting the schedule
.PARAMETER ScheduleType
    The desired schedule. If Daily is specified, DayOfWeek, DayOfMonth and DayNameOfMonth are ignored.
    If Weekly is specified, DayOfMonth is ignored. If Monthly is specified, DayOfWeek can be used to express nth Monday of the month
.PARAMETER DayOfWeek
    The day the maintenance window is defined for. ScheduleEnd can exceed the DayOfWeek
.PARAMETER DayOfMonth
    The nth day of a month. In conjunction with DayOfWeek uses e.g. the nth Monday of the month
.PARAMETER ScriptBlock
    The script block to generate a schedule from an external system, e.g. a CMDB, a file, the moon phase, ... Needs to return a hash table with the keys
    ScheduleStart and ScheduleEnd. Can optionally contain all parameters of the DSC resource except ScriptBlock to further control resource processing.
    If ScriptBlock is used, all parameters are ignored.
#>

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

        [parameter(Mandatory = $true)]
        [System.DateTime]
        $ScheduleEnd,

        [ValidateSet('Once', 'Daily', 'Weekly', 'Monthly')]
        [System.String[]]
        $ScheduleType,

        [ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
        [System.String]
        $DayOfWeek,

        [System.Int16]
        $DayOfMonth,

        [System.String]
        $ScriptBlock
    )

    $returnValue = @{
        ScheduleStart = $ScheduleStart
        ScheduleEnd   = $ScheduleEnd
        CurrentTime   = Get-Date
    }

    return $returnValue
}

<#
.SYNOPSIS
    Sets the current resource status
.PARAMETER ScheduleStart
    The start of the schedule. The property TimeOfDay is used for setting the schedule
.PARAMETER ScheduleEnd
    The end of the schedule. The property TimeOfDay is used for setting the schedule
.PARAMETER ScheduleType
    The desired schedule. If Daily is specified, DayOfWeek, DayOfMonth and DayNameOfMonth are ignored.
    If Weekly is specified, DayOfMonth is ignored. If Monthly is specified, DayOfWeek can be used to express nth Monday of the month
.PARAMETER DayOfWeek
    The day the maintenance window is defined for. ScheduleEnd can exceed the DayOfWeek
.PARAMETER DayOfMonth
    The nth day of a month. In conjunction with DayOfWeek uses e.g. the nth Monday of the month
.PARAMETER ScriptBlock
    The script block to generate a schedule from an external system, e.g. a CMDB, a file, the moon phase, ... Needs to return a hash table with the keys
    ScheduleStart and ScheduleEnd. Can optionally contain all parameters of the DSC resource except ScriptBlock to further control resource processing.
    If ScriptBlock is used, all parameters are ignored.
#>

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.DateTime]
        $ScheduleStart,

        [parameter(Mandatory = $true)]
        [System.DateTime]
        $ScheduleEnd,

        [ValidateSet('Once', 'Daily', 'Weekly', 'Monthly')]
        [System.String[]]
        $ScheduleType,

        [ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
        [System.String]
        $DayOfWeek,

        [System.Int16]
        $DayOfMonth,

        [System.String]
        $ScriptBlock
    )

    # Set should throw when in window to cancel processing
    $currentValues = Get-TargetResource @PSBoundParameters
    Write-Verbose -Message ('Nothing to set. Maintenance window start: {0}, maintenance window end: {1}. Current time {2}' -f 
        $ScheduleStart.TimeOfDay, $ScheduleEnd.TimeOfDay, $currentValues.CurrentTime)

    throw 'Outside of maintenance schedule. Aborting Set-TargetResource to trigger dependecies'
}

<#
.SYNOPSIS
    Tests the current resource status
.PARAMETER ScheduleStart
    The start of the schedule. The property TimeOfDay is used for setting the schedule
.PARAMETER ScheduleEnd
    The end of the schedule. The property TimeOfDay is used for setting the schedule
.PARAMETER ScheduleType
    The desired schedule. If Daily is specified, DayOfWeek, DayOfMonth and DayNameOfMonth are ignored.
    If Weekly is specified, DayOfMonth is ignored. If Monthly is specified, DayOfWeek can be used to express nth Monday of the month
.PARAMETER DayOfWeek
    The day the maintenance window is defined for. ScheduleEnd can exceed the DayOfWeek
.PARAMETER DayOfMonth
    The nth day of a month. In conjunction with DayOfWeek uses e.g. the nth Monday of the month
.PARAMETER ScriptBlock
    The script block to generate a schedule from an external system, e.g. a CMDB, a file, the moon phase, ... Needs to return a hash table with the keys
    ScheduleStart and ScheduleEnd. Can optionally contain all parameters of the DSC resource except ScriptBlock to further control resource processing.
    If ScriptBlock is used, all parameters are ignored.
#>

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

        [parameter(Mandatory = $true)]
        [System.DateTime]
        $ScheduleEnd,

        [ValidateSet('Once', 'Daily', 'Weekly', 'Monthly')]
        [System.String[]]
        $ScheduleType,

        [ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
        [System.String]
        $DayOfWeek,

        [System.Int16]
        $DayOfMonth,

        [System.String]
        $ScriptBlock
    )

    $currentValues = Get-TargetResource @PSBoundParameters

    $now = $currentValues.CurrentTime.TimeOfDay
    $shouldSkipSet = $true

    Write-Verbose -Message ('Start: {0}, End {1}, Current: {2}' -f $ScheduleStart.TimeOfDay, $ScheduleEnd.TimeOfDay, $now)

    if (-not [System.String]::IsNullOrWhiteSpace($ScriptBlock))
    {
        try
        {
            $executableScriptBlock = [scriptblock]::Create($ScriptBlock)
            $externalValues = $executableScriptBlock.Invoke()

            if ($externalValues.Count -gt 1)
            {
                throw 'More than one object has been returned from the external script block.'
            }

            if (-not ($externalValues[0].ContainsKey('ScheduleStart') -and $externalValues[0].ContainsKey('ScheduleEnd')))
            {
                throw 'Mandatory keys ScheduleStart and ScheduleEnd are missing'
            }

            $ScheduleStart = $externalValues[0].ScheduleStart
            $ScheduleEnd = $externalValues[0].ScheduleEnd

            if ($externalValues[0].ContainsKey('ScheduleType'))
            {
                $ScheduleType = $externalValues[0].ScheduleType
            }
            
            if ($externalValues[0].ContainsKey('DayOfWeek'))
            {
                $DayOfWeek = $externalValues[0].DayOfWeek
            }

            if ($externalValues[0].ContainsKey('DayOfMonth'))
            {
                $DayOfMonth = $externalValues[0].DayOfMonth
            }

            $Message = "External script returned the following key-value-pairs:`r`n{0}" -f (($externalValues[0].GetEnumerator() | ForEach-Object {"$($_.Key): $($_.Value)"} ) -join "`r`n") 
            Write-Verbose -Message $Message
        }
        catch
        {
            Write-Error -Message 'Could not create/execute script block from parameter value.' `
                -TargetObject $ScriptBlock `
                -RecommendedAction 'Load the script block into an editor of your choice and look for syntax errors.'
        }
    }

    if ($ScheduleStart.TimeOfDay -le $ScheduleEnd.TimeOfDay)
    {
        Write-Verbose -Message 'Timespans for start and end appear to be on the same day.'
        $shouldSkipSet = $now -ge $ScheduleStart.TimeOfDay -and $now -le $ScheduleEnd.TimeOfDay
    }
    else
    {
        Write-Verbose -Message 'Timespans for start and end appear to be on different days.'
        $shouldSkipSet = $now -ge $ScheduleStart.TimeOfDay -or $now -le $ScheduleEnd.TimeOfDay
    }

    if ($ScheduleType -eq 'Once')
    {
        Write-Verbose -Message ('Schedule is Once, testing if {0} is in maintenance window' -f $currentValues.CurrentTime)
        $shouldSkipSet = $currentValues.CurrentTime -ge $ScheduleStart -and $currentValues.CurrentTime -le $ScheduleEnd
    }

    if ($ScheduleType -eq 'Once' -or $ScheduleType -eq 'Daily')
    {
        return $shouldSkipSet
    }

    $addDays = 0

    # If we had rollover, compare current date -1 days with reference dates. Otherwise 0 is added.
    if ($now -le $ScheduleEnd.TimeOfDay -and -not ($ScheduleStart.TimeOfDay -le $ScheduleEnd.TimeOfDay) )
    {
        Write-Verbose -Message 'We had rollover. Substracting one day from all current values'
        $addDays = -1
    }

    # Logic OR: Never enter set method (i.e return $false) when either argument is $true
    if ($ScheduleType -eq 'Weekly')
    {
        Write-Verbose -Message ('Weekly schedule. Comparing {0} for equality with {1}' -f 
            $currentValues.CurrentTime.AddDays($addDays).DayOfWeek.ToString(), $DayOfWeek
        )

        $shouldSkipSet = $shouldSkipSet -and ($currentValues.CurrentTime.AddDays($addDays).DayOfWeek.ToString() -eq $DayOfWeek)
    }

    if ($ScheduleType -eq 'Monthly')
    {
        Write-Debug -Message 'Monthly schedule.'

        if ($PSBoundParameters.ContainsKey('DayOfMonth') -and $PSBoundParameters.ContainsKey('DayOfWeek'))
        {
            $dom = Get-DayOfMonth -Year $currentValues.CurrentTime.AddDays($addDays).Year -Month $currentValues.CurrentTime.AddDays($addDays).Month -Day $DayOfWeek -Occurrence $DayOfMonth

            Write-Verbose -Message ('Comparing {0} for equality with {1}' -f 
                $currentValues.CurrentTime.AddDays($addDays).Date,
                $dom.Date
            )
            $shouldSkipSet = $shouldSkipSet -and ($currentValues.CurrentTime.AddDays($addDays).Date -eq $dom.Date)
        }
        else
        {
            Write-Verbose -Message ('Comparing {0} for equality with {1}' -f 
                $currentValues.CurrentTime.AddDays($addDays).Day,
                $DayOfMonth
            )
            $shouldSkipSet = $shouldSkipSet -and ($currentValues.CurrentTime.AddDays($addDays).Day -eq $DayOfMonth)
        }
    }    

    return $shouldSkipSet
}


Export-ModuleMember -Function *-TargetResource