PSWsusSpringClean.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
Function Invoke-WsusSpringClean {
    <#
        .SYNOPSIS
        Performs additional WSUS server clean-up beyond the capabilities of the built-in tools.
        .DESCRIPTION
        Adds the ability to decline numerous additional commonly unneeded updates as well as discover potentially incorrectly declined updates.
        .PARAMETER RunDefaultTasks
        Performs all clean-up tasks except for declining any unneeded updates as defined in the included update catalogue CSV file.
 
        You can disable one or more of the default clean-up tasks by setting the associated switch parameter to false (e.g. -CompressUpdates:$false).
 
        You can perform a clean-up of unneeded updates by specifying the DeclineCategoriesInclude or DeclineCategoriesExclude parameter with your chosen categories.
 
        Also note that this does not perform a server synchronisation before clean-up or find suspect declined updates. These tasks can be included via their respective parameters.
        .PARAMETER SynchroniseServer
        Perform a synchronisation against the upstream server before running cleanup.
        .PARAMETER FindSuspectDeclines
        Scan all declined updates for any that may have been inadvertently declined.
 
        The returned suspect updates are those which:
         - Are not superseded or expired
         - Are not cluster or farm updates (if set to decline)
         - Are not in the filtered list of updates to decline from the bundled catalogue
        .PARAMETER DeclineClusterUpdates
        Decline any updates which are exclusively for failover clustering installations.
        .PARAMETER DeclineFarmUpdates
        Decline any updates which are exclusively for farm deployment installations.
        .PARAMETER DeclinePrereleaseUpdates
        Decline any updates which are exclusively for pre-release products (e.g. betas).
        .PARAMETER DeclineSecurityOnlyUpdates
        Decline any Security Only updates.
        .PARAMETER DeclineArchitectures
        Array of update architectures to decline.
 
        Valid options are: x64, ia64, arm64
 
        We don't support declining x86 updates as there's no mechanism to determine which updates are x86 specific versus multi-architecture.
        .PARAMETER DeclineCategoriesExclude
        Array of update categories in the bundled updates catalogue to not decline.
        .PARAMETER DeclineCategoriesInclude
        Array of update categories in the bundled updates catalogue to decline.
        .PARAMETER DeclineLanguagesExclude
        Array of update language codes to not decline.
        .PARAMETER DeclineLanguagesInclude
        Array of update language codes to decline.
        .PARAMETER CleanupObsoleteComputers
        Specifies that the cmdlet deletes obsolete computers from the database.
        .PARAMETER CleanupObsoleteUpdates
        Specifies that the cmdlet deletes obsolete updates from the database.
        .PARAMETER CleanupUnneededContentFiles
        Specifies that the cmdlet deletes unneeded update files.
        .PARAMETER CompressUpdates
        Specifies that the cmdlet deletes obsolete revisions to updates from the database.
        .PARAMETER DeclineExpiredUpdates
        Specifies that the cmdlet declines expired updates.
        .PARAMETER DeclineSupersededUpdates
        Specifies that the cmdlet declines superseded updates.
        .EXAMPLE
        PS C:\>$SuspectDeclines = Invoke-WsusSpringClean -RunDefaultTasks -FindSuspectDeclines
 
        Runs the default clean-up tasks & checks for declined updates that may not be intentional.
        .EXAMPLE
        PS C:\>Invoke-WsusSpringClean -DeclineCategoriesInclude @('Region - US', 'Superseded')
 
        Declines all unneeded updates in the "Region - US" & "Superseded" categories.
        .EXAMPLE
        PS C:\>Invoke-WsusSpringClean -DeclineLanguagesExclude @('en-AU')
 
        Declines all language specific updates excluding those for English (Australia).
        .EXAMPLE
        PS C:\>Invoke-WsusSpringClean -DeclineArchitectures @('arm64', 'ia64')
 
        Declines all architecture specific updates for ARM64 & IA64 (Itanium) systems.
        .NOTES
        The script intentionally avoids usage of most WSUS cmdlets provided by the UpdateServices module as many are extremely slow. This is particularly true of the Get-WsusUpdate cmdlet.
 
        The efficiency of the update declining logic could be substantially improved. That said, this script is not typically run frequently (~monthly), so this isn't a major priority.
        .LINK
        https://github.com/ralish/PSWsusSpringClean
    #>


    [CmdletBinding(DefaultParameterSetName='Default',SupportsShouldProcess)]
    Param(
        [Switch]$RunDefaultTasks,
        [Switch]$SynchroniseServer,
        [Switch]$FindSuspectDeclines,

        [Switch]$DeclineClusterUpdates,
        [Switch]$DeclineFarmUpdates,
        [Switch]$DeclinePrereleaseUpdates,
        [Switch]$DeclineSecurityOnlyUpdates,

        [String[]]$DeclineCategoriesExclude,
        [String[]]$DeclineCategoriesInclude,

        [ValidateScript({Test-WsusSpringCleanArchitectures -Architectures $_})]
        [String[]]$DeclineArchitectures,

        [ValidateScript({Test-WsusSpringCleanLanguageCodes -LanguageCodes $_})]
        [String[]]$DeclineLanguagesExclude,

        [ValidateScript({Test-WsusSpringCleanLanguageCodes -LanguageCodes $_})]
        [String[]]$DeclineLanguagesInclude,

        # Wrapping of Invoke-WsusServerCleanup
        [Switch]$CleanupObsoleteComputers,
        [Switch]$CleanupObsoleteUpdates,
        [Switch]$CleanupUnneededContentFiles,
        [Switch]$CompressUpdates,
        [Switch]$DeclineExpiredUpdates,
        [Switch]$DeclineSupersededUpdates
    )

    # Ensure that any errors we receive are considered fatal
    $ErrorActionPreference = 'Stop'

    if ($PSBoundParameters.ContainsKey('DeclineCategoriesExclude') -and $PSBoundParameters.ContainsKey('DeclineCategoriesInclude')) {
        throw 'Can only specify one of DeclineCategoriesExclude and DeclineCategoriesInclude.'
    }

    if ($PSBoundParameters.ContainsKey('DeclineLanguagesExclude') -and $PSBoundParameters.ContainsKey('DeclineLanguagesInclude')) {
        throw 'Can only specify one of DeclineLanguagesExclude and DeclineLanguagesInclude.'
    }

    if (!$script:WscMetadata) {
        Import-WsusSpringCleanMetadata
    }

    if ($RunDefaultTasks) {
        $DefaultTasks = @(
            'DeclineClusterUpdates',
            'DeclineFarmUpdates',
            'DeclinePrereleaseUpdates',
            'DeclineSecurityOnlyUpdates',

            'CleanupObsoleteComputers',
            'CleanupObsoleteUpdates',
            'CleanupUnneededContentFiles',
            'CompressUpdates',
            'DeclineExpiredUpdates',
            'DeclineSupersededUpdates'
        )

        foreach ($Task in $DefaultTasks) {
            if ($PSBoundParameters.ContainsKey($Task)) {
                Set-Variable -Name $Task -Value (Get-Variable -Name $Task).Value -WhatIf:$false
            } else {
                Set-Variable -Name $Task -Value $true -WhatIf:$false
            }
        }
    }

    # Regular expressions for declining certain types of updates
    $script:RegExClusterUpdates = ' Failover Clustering '
    $script:RegExFarmUpdates = ' Farm[- ]'
    $script:RegExPrereleaseUpdates = ' (Beta|Preview|RC1|Release Candidate) '
    $script:RegExSecurityOnlyUpdates = ' Security Only (Quality )?Update '

    # Determine which categories of updates to decline (if any)
    if ($PSBoundParameters.ContainsKey('DeclineCategoriesExclude') -or $PSBoundParameters.ContainsKey('DeclineCategoriesInclude')) {
        Import-WsusSpringCleanCatalogue
        $CatalogueCategories = $script:WscCatalogue.Category | Sort-Object | Get-Unique

        if ($PSBoundParameters.ContainsKey('DeclineCategoriesExclude')) {
            $DeclineCategories = $CatalogueCategories | Where-Object { $_ -notin $DeclineCategoriesExclude }
        } else {
            $DeclineCategories = $CatalogueCategories | Where-Object { $_ -in $DeclineCategoriesInclude }
        }
    }

    # Fetch the metadata for any architectures we're going to decline
    if ($PSBoundParameters.ContainsKey('DeclineArchitectures')) {
        $DeclineArchitecturesMetadata = @()
        foreach ($Architecture in $DeclineArchitectures) {
            $DeclineArchitecturesMetadata += $script:WscMetadata.SelectSingleNode('//Architectures/Architecture[@name="{0}"]' -f $Architecture)
        }
    }

    # Fetch the metadata for any languages we're going to decline
    if ($PSBoundParameters.ContainsKey('DeclineLanguagesExclude')) {
        $DeclineLanguagesMetadata = $script:WscMetadata.Languages.Language | Where-Object { $_.code -notin $DeclineLanguagesExclude }
    } elseif ($PSBoundParameters.ContainsKey('DeclineLanguagesInclude')) {
        $DeclineLanguagesMetadata = $script:WscMetadata.Languages.Language | Where-Object { $_.code -in $DeclineLanguagesInclude }
    }

    if ($SynchroniseServer) {
        Write-Host -ForegroundColor Green "`r`nStarting WSUS server synchronisation ..."
        Invoke-WsusServerSynchronisation
    }

    Write-Host -ForegroundColor Green "`r`nBeginning WSUS server cleanup (Phase 1) ..."
    $CleanupWrapperParams = @{
        CleanupObsoleteUpdates=$CleanupObsoleteUpdates
        CompressUpdates=$CompressUpdates
        DeclineExpiredUpdates=$DeclineExpiredUpdates
        DeclineSupersededUpdates=$DeclineSupersededUpdates
    }
    Invoke-WsusServerCleanupWrapper @CleanupWrapperParams

    Write-Host -ForegroundColor Green "`r`nBeginning WSUS server cleanup (Phase 2) ..."
    $SpringCleanParams = @{
        DeclineClusterUpdates=$DeclineClusterUpdates
        DeclineFarmUpdates=$DeclineFarmUpdates
        DeclinePrereleaseUpdates=$DeclinePrereleaseUpdates
        DeclineSecurityOnlyUpdates=$DeclineSecurityOnlyUpdates
    }

    if ($DeclineCategories) {
        $SpringCleanParams += @{DeclineCategories=$DeclineCategories}
    }

    if ($DeclineArchitecturesMetadata) {
        $SpringCleanParams += @{DeclineArchitectures=$DeclineArchitecturesMetadata}
    }

    if ($DeclineLanguagesMetadata) {
        $SpringCleanParams += @{DeclineLanguages=$DeclineLanguagesMetadata}
    }

    Invoke-WsusServerSpringClean @SpringCleanParams

    Write-Host -ForegroundColor Green "`r`nBeginning WSUS server cleanup (Phase 3) ..."
    $CleanupWrapperParams = @{
        CleanupObsoleteComputers=$CleanupObsoleteComputers
        CleanupUnneededContentFiles=$CleanupUnneededContentFiles
    }
    Invoke-WsusServerCleanupWrapper @CleanupWrapperParams

    if ($FindSuspectDeclines) {
        Get-WsusSuspectDeclines @SpringCleanParams
    }
}


Function Get-WsusSuspectDeclines {
    [CmdletBinding()]
    Param(
        [Switch]$DeclineClusterUpdates,
        [Switch]$DeclineFarmUpdates,
        [Switch]$DeclinePrereleaseUpdates,
        [Switch]$DeclineSecurityOnlyUpdates,

        [String[]]$DeclineCategories,
        [Xml.XmlElement[]]$DeclineArchitectures,
        [Xml.XmlElement[]]$DeclineLanguages
    )

    $WsusServer = Get-WsusServer
    $UpdateScope = New-Object -TypeName Microsoft.UpdateServices.Administration.UpdateScope

    Write-Host -ForegroundColor Green '[*] Retrieving declined updates ...'
    $UpdateScope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::Declined
    $WsusDeclined = $WsusServer.GetUpdates($UpdateScope)

    # Ignore all updates corresponding to architectures, categories or languages we declined
    $IgnoredCatalogueCategories = $script:WscCatalogue | Where-Object { $_.Category -in $DeclineCategories }
    $IgnoredArchitecturesRegEx = ' ({0})' -f [String]::Join('|', $DeclineArchitectures.regex)
    $IgnoredLanguagesRegEx = ' [\[]?({0})(_LP|_LIP)?[\]]?' -f [String]::Join('|', $DeclineLanguages.code)

    Write-Host -ForegroundColor Green '[*] Finding suspect declined updates ...'
    $SuspectDeclines = @()
    foreach ($Update in $WsusDeclined) {
        # Ignore superseded and expired updates
        if ($Update.IsSuperseded -or $Update.PublicationState -eq 'Expired') {
            continue
        }

        # Ignore cluster updates if they were declined
        if ($DeclineClusterUpdates -and $Update.Title -match $RegExClusterUpdates) {
            continue
        }

        # Ignore farm updates if they were declined
        if ($DeclineFarmUpdates -and $Update.Title -match $RegExFarmUpdates) {
            continue
        }

        # Ignore pre-release updates if they were declined
        if ($DeclinePrereleaseUpdates -and $Update.Title -match $RegExPrereleaseUpdates) {
            continue
        }

        # Ignore Security Only Quality updates if they were declined
        if ($DeclineSecurityOnlyUpdates -and $Update.Title -match $RegExSecurityOnlyUpdates) {
            continue
        }

        # Ignore any update categories which were declined
        if ($Update.Title -in $IgnoredCatalogueCategories.Title) {
            continue
        }

        # Ignore any update architectures which were declined
        if ($Update.Title -match $IgnoredArchitecturesRegEx) {
            continue
        }

        # Ignore any update languages which were declined
        if ($Update.Title -match $IgnoredLanguagesRegEx) {
            continue
        }

        $SuspectDeclines += $Update
    }

    return $SuspectDeclines
}


Function Import-WsusSpringCleanMetadata {
    [CmdletBinding()]
    Param()

    Write-Verbose -Message '[*] Importing module metadata ...'
    $MetadataPath = Join-Path -Path $PSScriptRoot -ChildPath 'PSWsusSpringClean.xml'
    $script:WscMetadata = ([Xml](Get-Content -Path $MetadataPath)).PSWsusSpringClean
}


Function Invoke-WsusDeclineUpdatesByCatalogue {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory)]
        [Microsoft.UpdateServices.Internal.BaseApi.Update[]]$Updates,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [String]$Category
    )

    Write-Host -ForegroundColor Green ('[*] Declining updates in category: {0}' -f $Category)
    $UpdatesToDecline = $script:WscCatalogue | Where-Object { $_.Category -eq $Category }
    $MatchingUpdates = $Updates | Where-Object { $_.Title -in $UpdatesToDecline.Title }

    foreach ($Update in $MatchingUpdates) {
        if ($PSCmdlet.ShouldProcess($Update.Title, 'Decline')) {
            Write-Host -ForegroundColor Cyan ('[-] Declining update: {0}' -f $Update.Title)
            $Update.Decline()
        }
    }
}


Function Invoke-WsusDeclineUpdatesByRegEx {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory)]
        [Microsoft.UpdateServices.Internal.BaseApi.Update[]]$Updates,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [String]$RegEx
    )

    foreach ($Update in $Updates) {
        if ($Update.Title -match $RegEx) {
            if ($PSCmdlet.ShouldProcess($Update.Title, 'Decline')) {
                Write-Host -ForegroundColor Cyan ('[-] Declining update: {0}' -f $Update.Title)
                $Update.Decline()
            }
        }
    }
}


Function Invoke-WsusServerCleanupWrapper {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        [Switch]$CleanupObsoleteComputers,
        [Switch]$CleanupObsoleteUpdates,
        [Switch]$CleanupUnneededContentFiles,
        [Switch]$CompressUpdates,
        [Switch]$DeclineExpiredUpdates,
        [Switch]$DeclineSupersededUpdates
    )

    if ($CleanupObsoleteComputers) {
        Write-Host -ForegroundColor Green '[*] Deleting obsolete computers ...'
        Write-Host (Invoke-WsusServerCleanup -CleanupObsoleteComputers)
    }

    if ($CleanupObsoleteUpdates) {
        Write-Host -ForegroundColor Green '[*] Deleting obsolete updates ...'
        Write-Host (Invoke-WsusServerCleanup -CleanupObsoleteUpdates)
    }

    if ($CleanupUnneededContentFiles) {
        Write-Host -ForegroundColor Green '[*] Deleting unneeded update files ...'
        Write-Host (Invoke-WsusServerCleanup -CleanupUnneededContentFiles)
    }

    if ($CompressUpdates) {
        Write-Host -ForegroundColor Green '[*] Deleting obsolete update revisions ...'
        Write-Host (Invoke-WsusServerCleanup -CompressUpdates)
    }

    if ($DeclineExpiredUpdates) {
        Write-Host -ForegroundColor Green '[*] Declining expired updates ...'
        Write-Host (Invoke-WsusServerCleanup -DeclineExpiredUpdates)
    }

    if ($DeclineSupersededUpdates) {
        Write-Host -ForegroundColor Green '[*] Declining superseded updates ...'
        Write-Host (Invoke-WsusServerCleanup -DeclineSupersededUpdates)
    }
}


Function Invoke-WsusServerSynchronisation {
    [CmdletBinding(SupportsShouldProcess)]
    Param()

    $WsusServer = Get-WsusServer

    if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, 'WSUS synchronization')) {
        $SyncStatus = $WsusServer.GetSubscription().GetSynchronizationStatus()
        if ($SyncStatus -eq 'NotProcessing') {
            $WsusServer.GetSubscription().StartSynchronization()
        } elseif ($SyncStatus -eq 'Running') {
            Write-Warning -Message "[!] A synchronisation appears to already be running! We'll wait for this one to complete ..."
        } else {
            throw ('WSUS server returned unknown synchronisation status: {0}' -f $SyncStatus)
        }

        do {
            Start-Sleep -Seconds 5
        } while ($WsusServer.GetSubscription().GetSynchronizationStatus() -eq 'Running')

        $SyncResult = $WsusServer.GetSubscription().GetLastSynchronizationInfo().Result
        if ($SyncResult -ne 'Succeeded') {
            throw ('WSUS server synchronisation completed with unexpected result: {0}' -f $SyncResult)
        }
    }
}


Function Invoke-WsusServerSpringClean {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        [Switch]$DeclineClusterUpdates,
        [Switch]$DeclineFarmUpdates,
        [Switch]$DeclinePrereleaseUpdates,
        [Switch]$DeclineSecurityOnlyUpdates,

        [String[]]$DeclineCategories,
        [Xml.XmlElement[]]$DeclineArchitectures,
        [Xml.XmlElement[]]$DeclineLanguages
    )

    $WsusServer = Get-WsusServer
    $UpdateScope = New-Object -TypeName Microsoft.UpdateServices.Administration.UpdateScope

    Write-Host -ForegroundColor Green '[*] Retrieving approved updates ...'
    $UpdateScope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::LatestRevisionApproved
    $WsusApproved = $WsusServer.GetUpdates($UpdateScope)

    Write-Host -ForegroundColor Green '[*] Retrieving unapproved updates ...'
    $UpdateScope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::NotApproved
    $WsusUnapproved = $WsusServer.GetUpdates($UpdateScope)

    $WsusAnyExceptDeclined = $WsusApproved + $WsusUnapproved

    if ($DeclineClusterUpdates) {
        Write-Host -ForegroundColor Green '[*] Declining cluster updates ...'
        Invoke-WsusDeclineUpdatesByRegEx -Updates $WsusAnyExceptDeclined -RegEx $script:RegExClusterUpdates
    }

    if ($DeclineFarmUpdates) {
        Write-Host -ForegroundColor Green '[*] Declining farm updates ...'
        Invoke-WsusDeclineUpdatesByRegEx -Updates $WsusAnyExceptDeclined -RegEx $script:RegExFarmUpdates
    }

    if ($DeclinePrereleaseUpdates) {
        Write-Host -ForegroundColor Green '[*] Declining pre-release updates ...'
        Invoke-WsusDeclineUpdatesByRegEx -Updates $WsusAnyExceptDeclined -RegEx $script:RegExPrereleaseUpdates
    }

    if ($DeclineSecurityOnlyUpdates) {
        Write-Host -ForegroundColor Green '[*] Declining Security Only updates ...'
        Invoke-WsusDeclineUpdatesByRegEx -Updates $WsusAnyExceptDeclined -RegEx $script:RegExSecurityOnlyUpdates
    }

    if ($PSBoundParameters.ContainsKey('DeclineCategories')) {
        foreach ($Category in $DeclineCategories) {
            Invoke-WsusDeclineUpdatesByCatalogue -Updates $WsusAnyExceptDeclined -Category $Category
        }
    }

    if ($PSBoundParameters.ContainsKey('DeclineArchitectures')) {
        foreach ($Architecture in $DeclineArchitectures) {
            Write-Host -ForegroundColor Green ('[*] Declining updates with architecture: {0}' -f $Architecture.name)
            $ArchitectureRegEx = ' ({0})' -f $Architecture.regex
            Invoke-WsusDeclineUpdatesByRegEx -Updates $WsusAnyExceptDeclined -RegEx $ArchitectureRegEx
        }
    }

    if ($PSBoundParameters.ContainsKey('DeclineLanguages')) {
        foreach ($Language in $DeclineLanguages) {
            Write-Host -ForegroundColor Green ('[*] Declining updates with language: {0}' -f $Language.code)
            $LanguageRegEx = ' [\[]?{0}(_LP|_LIP)?[\]]?' -f $Language.code
            Invoke-WsusDeclineUpdatesByRegEx -Updates $WsusAnyExceptDeclined -RegEx $LanguageRegEx
        }
    }
}


Function Test-WsusSpringCleanArchitectures {
    Param(
        [Parameter(Mandatory)]
        [String[]]$Architectures
    )

    if (!$script:WscMetadata) {
        Import-WsusSpringCleanMetadata
    }

    $KnownArchitectures = $script:WscMetadata.Architectures.Architecture.name
    foreach ($Architecture in $Architectures) {
        if ($Architecture -notin $KnownArchitectures) {
            throw 'Unknown architecture specified: {0}' -f $Architecture
        }
    }

    return $true
}


Function Test-WsusSpringCleanLanguageCodes {
    Param(
        [Parameter(Mandatory)]
        [String[]]$LanguageCodes
    )

    if (!$script:WscMetadata) {
        Import-WsusSpringCleanMetadata
    }

    $KnownLanguageCodes = $script:WscMetadata.Languages.Language.code
    foreach ($LanguageCode in $LanguageCodes) {
        if ($LanguageCode -notin $KnownLanguageCodes) {
            throw 'Unknown language code specified: {0}' -f $LanguageCode
        }
    }

    return $true
}


Function ConvertTo-WsusSpringCleanCatalogue {
    Param(
        [Parameter(Mandatory,ValueFromPipeline)]
        [Microsoft.UpdateServices.Internal.BaseApi.Update[]]$Updates
    )

    Process {
        foreach ($Update in $Updates) {
            [String[]]$ProductTitles = @()
            foreach ($ProductTitle in $Update.ProductTitles) {
                $ProductTitles += $ProductTitle
            }

            [PSCustomObject]@{
                'Category'      = 'Unknown'
                'Title'         = $Update.Title
                'ProductTitles' = [String]::Join(', ', $ProductTitles)
            }
        }
    }
}


Function Import-WsusSpringCleanCatalogue {
    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [String]$CataloguePath
    )

    if (!$CataloguePath) {
        $CataloguePath = Join-Path -Path $PSScriptRoot -ChildPath 'PSWsusSpringClean.csv'
    }

    Write-Verbose -Message '[*] Importing update catalogue ...'
    $script:WscCatalogue = Import-Csv -Path $CataloguePath
}


Function Test-WsusSpringCleanCatalogue {
    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [String]$CataloguePath
    )

    Import-WsusSpringCleanCatalogue @PSBoundParameters

    Write-Host -ForegroundColor Green '[*] Retrieving all updates ...'
    $WsusServer = Get-WsusServer
    $WsusUpdateScope = New-Object -TypeName Microsoft.UpdateServices.Administration.UpdateScope
    $WsusUpdateScope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::Any
    $WsusUpdates = $WsusServer.GetUpdates($WsusUpdateScope)

    Write-Host -ForegroundColor Green '[*] Scanning for updates only present in catalogue ...'
    $CatalogueOnly = @()
    foreach ($Update in $script:WscCatalogue) {
        if ($Update.Title -notin $WsusUpdates.Title) {
            $CatalogueOnly += $Update
        }
    }

    return $CatalogueOnly
}