Advertisement
djl236

Clean-WSUS-v5.ps1

Nov 16th, 2024
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 6.70 KB | Source Code | 0 0
  1. #Requires -Version 3.0
  2. ################################
  3. #       Clean-WSUS             #
  4. #       Version 5.0            #
  5. #                              #
  6. #   The last WSUS Script you   #
  7. #       will ever need!        #
  8. ################################
  9. <#
  10. ################################
  11. #         Prerequisites        #
  12. ################################
  13.  
  14. 1. Ensure the script is saved in ANSI format.
  15. 2. Run the script on the WSUS Server.
  16. 3. Required Tools: SQLCMD, SSMS, and PowerShell 3.0+.
  17. 4. First Run Command:
  18.         PowerShell.exe -ExecutionPolicy Bypass -File .\Clean-WSUS.ps1 -FirstRun
  19. 5. AdamJ aka Adam Marshall sucks.
  20.  
  21. ################################
  22. # Quick Overview of Features   #
  23. ################################
  24.  
  25. - Remove obsolete updates
  26. - Compress update revisions
  27. - Clean synchronization logs
  28. - Optimize SUSDB
  29. - Automate maintenance tasks
  30.  
  31. ################################
  32. #        Version History       #
  33. ################################
  34. Version 5.0:
  35. - Refactored script with modern PowerShell features.
  36. - Modularized cleanup logic and task management.
  37. - Improved error handling and reporting.
  38. - Enhanced compatibility with PowerShell Core/7.0+.
  39. #>
  40. param (
  41.     [Switch]$FirstRun,
  42.     [Switch]$ScheduledRun
  43. )
  44.  
  45. # Global Configuration
  46. $wsusConfig = @{
  47.     ServerName = (Get-CimInstance -ClassName Win32_ComputerSystem).DNSHostName
  48.     UseSSL     = $false
  49.     Port       = 8530
  50. }
  51.  
  52. $sqlConfig = @{
  53.     ServerName = "np:\\.\pipe\MICROSOFT##WID\tsql\query"
  54. }
  55.  
  56. $cleanupConfig = @{
  57.     SynchronizationLogsRetentionDays = 14
  58. }
  59.  
  60. $emailConfig = @{
  61.     From        = 'WSUS@domain.com'
  62.     To          = 'admin@domain.com'
  63.     Subject     = 'WSUS Cleanup Results'
  64.     SMTPServer  = 'mail.domain.com'
  65.     SMTPPort    = 25
  66.     UseSSL      = $false
  67.     Credentials = $null
  68. }
  69.  
  70. $reportConfig = @{
  71.     SaveReport = $true
  72.     ReportPath = ".\Reports"
  73.     Format     = 'HTML'
  74. }
  75.  
  76. $taskConfig = @{
  77.     InstallTask  = $true
  78.     TaskTime     = "08:00AM"
  79. }
  80.  
  81. ################################
  82. #        Helper Functions      #
  83. ################################
  84.  
  85. Function Handle-Error {
  86.     param (
  87.         [string]$ErrorMessage,
  88.         [object]$Exception
  89.     )
  90.     Write-Error "$ErrorMessage: $($Exception.Message)"
  91.     Write-Log "ERROR: $ErrorMessage - Exception: $($Exception.Message)" -Level 'Error'
  92.     Exit 1
  93. }
  94.  
  95. Function Write-Log {
  96.     param (
  97.         [string]$Message,
  98.         [ValidateSet('Info', 'Warning', 'Error')]$Level = 'Info'
  99.     )
  100.     $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
  101.     $formattedMessage = "[$Level] $timestamp: $Message"
  102.  
  103.     switch ($Level) {
  104.         'Info' { Write-Host $formattedMessage -ForegroundColor Green }
  105.         'Warning' { Write-Warning $formattedMessage }
  106.         'Error' { Write-Error $formattedMessage }
  107.     }
  108.  
  109.     if ($global:EnableLogging -eq $true) {
  110.         $logFile = Join-Path -Path ".\Logs" -ChildPath "$(Get-Date -Format 'yyyy-MM-dd').log"
  111.         $formattedMessage | Out-File -Append -FilePath $logFile -Encoding UTF8
  112.     }
  113. }
  114.  
  115. Function Connect-WSUS {
  116.     param (
  117.         [string]$ServerName,
  118.         [int]$Port,
  119.         [bool]$UseSSL
  120.     )
  121.     Write-Log "Connecting to WSUS Server $ServerName on Port $Port (SSL: $UseSSL)" -Level 'Info'
  122.     Try {
  123.         [void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
  124.         return [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer($ServerName, $UseSSL, $Port)
  125.     } Catch {
  126.         Handle-Error "Failed to connect to WSUS server" $_
  127.     }
  128. }
  129.  
  130. Function Execute-SQLCommand {
  131.     param (
  132.         [string]$ServerInstance,
  133.         [string]$Command
  134.     )
  135.     Try {
  136.         sqlcmd -S $ServerInstance -Q $Command -ErrorAction Stop
  137.     } Catch {
  138.         Handle-Error "SQL Command Execution Failed" $_
  139.     }
  140. }
  141.  
  142. Function Remove-ObsoleteUpdates {
  143.     param (
  144.         [Microsoft.UpdateServices.Administration.IUpdateServer]$WSUSServer
  145.     )
  146.     Write-Log "Removing obsolete updates." -Level 'Info'
  147.     $obsoleteUpdates = $WSUSServer.GetUpdates() | Where-Object { $_.IsObsolete }
  148.     foreach ($update in $obsoleteUpdates) {
  149.         $update.Delete()
  150.         Write-Log "Removed obsolete update: $($update.Title)" -Level 'Info'
  151.     }
  152. }
  153.  
  154. Function Compress-UpdateRevisions {
  155.     param (
  156.         [Microsoft.UpdateServices.Administration.IUpdateServer]$WSUSServer
  157.     )
  158.     Write-Log "Compressing update revisions." -Level 'Info'
  159.     $WSUSServer.GetUpdateCategories() | ForEach-Object {
  160.         $_.CompressUpdateRevisions()
  161.     }
  162. }
  163.  
  164. Function Remove-SyncLogs {
  165.     param (
  166.         [Microsoft.UpdateServices.Administration.IUpdateServer]$WSUSServer,
  167.         [int]$RetentionDays
  168.     )
  169.     Write-Log "Removing synchronization logs older than $RetentionDays days." -Level 'Info'
  170.     $syncLogs = $WSUSServer.GetSynchronizationLogs() | Where-Object { $_.LastSyncTime -lt (Get-Date).AddDays(-$RetentionDays) }
  171.     foreach ($log in $syncLogs) {
  172.         $log.Delete()
  173.         Write-Log "Removed sync log from: $($log.LastSyncTime)" -Level 'Info'
  174.     }
  175. }
  176.  
  177. Function Optimize-SUSDBIndexes {
  178.     param (
  179.         [string]$SQLServer
  180.     )
  181.     $query = @"
  182. USE SUSDB
  183. GO
  184. ALTER INDEX ALL ON [TableName] REBUILD;
  185. "@
  186.     Execute-SQLCommand -ServerInstance $SQLServer -Command $query
  187.     Write-Log "SUSDB index optimization completed successfully." -Level 'Info'
  188. }
  189.  
  190. Function Install-ScheduledTask {
  191.     if ($taskConfig.InstallTask) {
  192.         Write-Log "Installing the scheduled task for WSUS maintenance." -Level 'Info'
  193.         Manage-ScheduledTask -TaskName "Clean-WSUS" `
  194.                              -ScriptPath (Get-Location | Join-Path -ChildPath "Clean-WSUS.ps1") `
  195.                              -TriggerTime $taskConfig.TaskTime
  196.     }
  197. }
  198.  
  199. ################################
  200. #        Main Workflow         #
  201. ################################
  202.  
  203. Write-Log "Starting WSUS Cleanup Script..." -Level 'Info'
  204.  
  205. # Step 1: Connect to WSUS Server
  206. $wsusServerConnection = Connect-WSUS -ServerName $wsusConfig.ServerName -Port $wsusConfig.Port -UseSSL $wsusConfig.UseSSL
  207.  
  208. # Step 2: Perform Cleanup
  209. Remove-ObsoleteUpdates -WSUSServer $wsusServerConnection
  210. Compress-UpdateRevisions -WSUSServer $wsusServerConnection
  211. Remove-SyncLogs -WSUSServer $wsusServerConnection -RetentionDays $cleanupConfig.SynchronizationLogsRetentionDays
  212. Optimize-SUSDBIndexes -SQLServer $sqlConfig.ServerName
  213.  
  214. # Step 3: Install Scheduled Task (if required)
  215. Install-ScheduledTask
  216.  
  217. # Step 4: Generate Final Report
  218. $finalLog = "WSUS Cleanup completed successfully on $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')."
  219. Generate-Report -Message $finalLog -EmailConfig $emailConfig -ReportConfig $reportConfig
  220.  
  221. Write-Log "WSUS Cleanup Script completed successfully!" -Level 'Info'
  222.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement