-
Notifications
You must be signed in to change notification settings - Fork 7
/
wsus-cleanup-updates-v4.ps1
266 lines (201 loc) · 7.38 KB
/
wsus-cleanup-updates-v4.ps1
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
<#
WSUS-CLEANUP-UPDATES
Runs WSUS cleanup task using stored procedures in WSUS database
thus avoiding timeout errors that may occur when running WSUS Cleanup Wizard.
The script is intended to run as a scheduled task on WSUS server
but can also be used remotely. $SqlServer and $SqlDB variables
must be defined before running the script on a server without WSUS.
Version 4
Version history:
4 Added database connection state check before deleting an
unused update: the script will now attempt to reestablish
connection if broken.
#>
##########################
# Configurable parameters
$SqlServer = "" # SQL server host name; leave empty to use information from local registry
$SqlDB = "SUSDB" # WSUS database name
$SkipFileCleanup = $SqlServer -ne ""
$log_source = "WSUS cleanup Task" # Event log source name
$log_debugMode = $true # set to false to suppress console output
##########################
$ErrorActionPreference = "Stop"
# basic logging facility
function log_init{
if ( -not [System.Diagnostics.EventLog]::SourceExists($log_source) ){
[System.Diagnostics.EventLog]::CreateEventSource($log_source, "Application")
}
}
function log( [string] $msg, [int32] $eventID, [System.Diagnostics.EventLogEntryType] $level ){
Write-EventLog -LogName Application -Source $log_source -EntryType $level -EventId $eventID -Message $msg
if ( $log_debugMode ){
switch ($level){
Warning {Write-Host $msg -ForegroundColor Yellow }
Error { Write-Host $msg -ForegroundColor Red }
default { Write-Host $msg -ForegroundColor Gray }
}
}
}
function dbg( [string] $msg ){
if ( $log_debugMode ){
log "DBG: $msg" 300 "Information"
}
}
log_init
#########################
function DeclineExpiredUpdates( $dbconn ){
log "Declining expired updates" 1 "Information"
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $dbconn
$Command.CommandTimeout = 3600
$Command.CommandText = "EXEC spDeclineExpiredUpdates"
try{
$Command.ExecuteNonQuery() | Out-Null
}
catch{
$script:errorCount++
log "Exception declining expired updates:`n$_" 99 "Error"
}
}
#########################
function DeclineSupersededUpdates( $dbconn ){
log "Declining superseded updates" 1 "Information"
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $dbconn
$Command.CommandTimeout = 1800
$Command.CommandText = "EXEC spDeclineSupersededUpdates"
try{
$Command.ExecuteNonQuery() | Out-Null
}
catch{
$script:errorCount++
log "Exception declining superseded updates:`n$_" 99 "Error"
}
}
#######################
function DeleteObsoleteUpdates( $dbconn ){
Log "Reading obsolete update list." 1 "Information"
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $dbconn
$Command.CommandTimeout = 600
$Command.CommandText = "EXEC spGetObsoleteUpdatesToCleanup"
$reader = $Command.ExecuteReader()
$table = New-Object System.Data.DataTable
$table.Load($reader)
$updatesTotal = $table.Rows.Count
log "Found $updatesTotal updates that can be deleted." 1 "Information"
$updatesProcessed=0
$Command.CommandTimeout = 300
foreach( $row in $table.Rows ){
try{
if ( $dbconn.State -ne [System.Data.ConnectionState]::Open ){
log "Re-opening database connection" 2 "Warning"
$dbconn.Open()
}
$updatesProcessed++
log "Deleting update $($row.localUpdateID) ($updatesProcessed of $updatesTotal)" 1 "Information"
$Command.CommandText = "exec spDeleteUpdate @LocalUpdateID=$($row.localUpdateID)"
$Command.ExecuteNonQuery() | Out-Null
}
catch{
$errorCount++
log "Error deleting update $($row.localUpdateID):`n$_" 8 "Warning"
}
}
}
###################
function DbConnectionString{
$WsusSetupKey = "HKLM:\SOFTWARE\Microsoft\Update Services\Server\Setup"
if ( $script:SqlServer -eq "" ){
$server = Get-ItemProperty -path $WsusSetupKey -Name "SqlServerName" -ErrorAction SilentlyContinue
$db = Get-ItemProperty -path $WsusSetupKey -Name "SqlDatabaseName" -ErrorAction SilentlyContinue
if ( ! $server ){
throw "Cannot determine SQL server name"
}
$script:SqlServer = $server.SqlServerName
$script:SqlDB = $db.SqlDatabaseName
}
if ( $script:SqlServer -match "microsoft##" ){
return "data source=\\.\pipe\$script:SqlServer\tsql\query;Integrated Security=True;database='$script:SqlDB';Network Library=dbnmpntw"
}
else{
return "server='$script:SqlServer';database='$script:SqlDB';trusted_connection=true;"
}
}
##############
function DeleteUnusedContent{
log "Deleting unneeded content files" 1 "Information"
try{
Import-Module UpdateServices
$status = Invoke-WsusServerCleanup -CleanupUnneededContentFiles
log "Done deleting unneeded content files: $status" 1 "Information"
}
catch{
$script:errorCount++
log "Exception deleting unneeded content files:`n$_" 99 "Error"
}
}
###################
function DeleteInactiveComputers( $DbConn ){
log "Removing obsolete computers" 1 "Information"
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $dbconn
$Command.CommandTimeout = 1800
$Command.CommandText = "EXEC spCleanupObsoleteComputers"
try{
$Command.ExecuteNonQuery() | Out-Null
}
catch{
$script:errorCount++
log "Exception removing obsolete computers:`n$_" 99 "Error"
}
}
function RestartWsusService{
log "Stopping IIS.." 1 "Information"
try{
Stop-Service W3SVC -Force
try{
log "Restarting WSUS service.." 1 "Information"
Restart-Service WsusService -Force
}
finally{
log "Starting IIS..." 1 "Information"
Start-Service W3SVC
}
}
catch{
$script:errorCount++
log "Error restarting WSUS services:`n$_" 99 "Error"
}
Start-Sleep -Seconds 30
}
<#------------------------------------------------
MAIN
-------------------------------------------------#>
$timeExecStart = Get-Date
$errorCount = 0
try{
$Conn = New-Object System.Data.SQLClient.SQLConnection
$Conn.ConnectionString = DbConnectionString
log "Connecting to database $SqlDB on $SqlServer" 1 "Information"
$Conn.Open()
try{
DeclineExpiredUpdates $Conn
DeclineSupersededUpdates $Conn
DeleteObsoleteUpdates $Conn
DeleteInactiveComputers $Conn
RestartWsusService
if ( ! $SkipFileCleanup ) {
DeleteUnusedContent
}
}
finally{
$Conn.Close()
}
}
catch{
$errorCount++
log "Unhandled exception:`n$_" 100 "Error"
}
$time_exec = ( Get-Date ) - $timeExecStart
log "Completed script execution with $errorCount error(s)`nExecution time $([math]::Round($time_exec.TotalHours)) hours and $([math]::Round($time_exec.totalMinutes)) minutes." 1 "Information"