forked from bmparson/PS-ScheduledTaskCheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScheduledTaskCheck.ps1
412 lines (403 loc) · 23.5 KB
/
ScheduledTaskCheck.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
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
#Global Variable Declaration
$taskarray = @()
$failedTasks = @()
$taskReport = @()
$servername = Get-Content "c:\scripts\ScheduledTaskCheck\servers.txt"
$previousFailedTasks = $null
$msg = $null
$shutdownMsg = $null
$threshold = $null
$reboot = $false
#Function to get all Folders and SubFolders in the Scheduler Service
function Get-AllTaskSubFolders {
[cmdletbinding()]
param (
# Set to use $Schedule as default parameter so it automatically list all files
# For current schedule object if it exists.
$FolderRef = $Schedule.getfolder("\")
)
if ($FolderRef.Path -eq '\') {
$FolderRef
}
if (-not $RootFolder) {
$ArrFolders = @()
if(($Folders = $folderRef.getfolders(1))) {
$Folders | ForEach-Object {
$ArrFolders += $_
if($_.getfolders(1)) {
Get-AllTaskSubFolders -FolderRef $_
}
}
}
$ArrFolders
}
}
#Import Previous Failed Tasks and Threshold File for Record keeping and Messaging logic
if(Test-Path "c:\scripts\ScheduledTaskCheck\failedtaskreport.csv")
{
$previousFailedTasks = Import-Csv "c:\scripts\ScheduledTaskCheck\failedtaskreport.csv"
}
if(Test-Path "c:\scripts\ScheduledTaskCheck\taskfailurethreshold.csv")
{
$threshold = Import-Csv "c:\scripts\ScheduledTaskCheck\taskfailurethreshold.csv"
}
#Loop through each server defined in servers.txt
foreach($server in $servername)
{
$boot=(get-date) - (gcim Win32_OperatingSystem -computername $server).LastBootUpTime
if($boot.days -eq 0 -and $boot.hours -eq 0 -and $boot.minutes -le 5)
{
$reboot = $true
}
Else
{
$reboot = $false
}
if(-not $reboot)
{
#Connect to Scheduler Service on Server
$schedule = new-object -com("Schedule.Service")
$schedule.connect($server)
#Get all Enabled Tasks
$AllFolders = Get-AllTaskSubFolders
foreach($folder in $AllFolders)
{
#Exclude Microsoft Created Tasks
if($folder.path -notlike "\Microsoft*")
{
$tasks = $schedule.getfolder($folder.path).gettasks(0)
$ourtasks = $tasks |select Name,Path,LastRunTime,LastTaskResult,State,@{Name="RunAs";Expression={[xml]$xml = $_.xml ; $xml.Task.Principals.principal.userID}},@{Name="Server";Expression={$server}}
$reportTasks = $tasks |select Name,State,XML,@{Name="RunAs";Expression={[xml]$xml = $_.xml ; $xml.Task.Principals.principal.userID}},@{Name="Command";Expression={[xml]$xml = $_.xml ; $xml.Task.Actions.exec.command}},@{Name="Arguments";Expression={[xml]$xml = $_.xml ; $xml.Task.Actions.exec.arguments}},@{Name="Triggers";Expression={[xml]$xml = $_.xml ; $xml.Task.triggers}},@{Name="Server";Expression={$server}}
$enabledTasks = $ourtasks | where {$_.state -ne 1}
$enabledReportTasks = $reportTasks | where {$_.state -ne 1}
#Filter all Enabled Tasks for unimportant tasknames and put into an array
foreach($task in $enabledtasks)
{
$object = New-Object system.object
$object | add-member -type NoteProperty -name Name -Value $task.name
$object | add-member -type NoteProperty -name Path -Value $task.path
$object | add-member -type NoteProperty -name LastRunTime -Value $task.lastruntime
$object | add-member -type NoteProperty -name LastTaskResult -Value $task.LastTaskResult
$object | add-member -type NoteProperty -name State -Value $task.state
$object | add-member -type NoteProperty -name RunAs -Value ($task | where {$_.runas -ne $null} | foreach-object {$objSID = New-Object System.Security.Principal.SecurityIdentifier ($_.runas)
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
$objuser.value})
$object | add-member -type NoteProperty -name Server -Value $task.server
$object | add-member -type NoteProperty -name TimesFailed -Value $null
$object | add-member -type NoteProperty -name MsgSent -Value $null
$object | add-member -type NoteProperty -name ShutdownStateCount -Value $null
if($object.name -notlike "Adobe*" -and $object.name -notlike "Optimize Start Menu*" -and $object.name -notlike "GoogleUpdate*")
{
$taskarray += $object
}
}
foreach($task in $enabledReportTasks)
{
[xml]$xml=$task.xml
$triggerType=$xml.task.Triggers.ChildNodes.name
$trigger= $null
$months = $null
$days = $null
$weeks = $null
if($triggerType -eq "CalendarTrigger")
{
$StartBoundary = $xml.task.Triggers.CalendarTrigger.StartBoundary
$StartBoundary = $StartBoundary.Split("T")
if($xml.task.Triggers.CalendarTrigger.ChildNodes.name.Contains("Repetition"))
{
$Interval = $xml.task.Triggers.CalendarTrigger.Repetition.Interval
$Interval = $Interval -replace "PT"
$Interval = $Interval -replace "H", " Hours"
$Interval = $Interval -replace "D", " Days"
$Interval = $Interval -replace "M", " Minutes"
$Interval = " Repeat every " + $Interval
if($xml.task.Triggers.CalendarTrigger.Repetition.ChildNodes.name.Contains("Duration"))
{
$Duration = $xml.task.Triggers.CalendarTrigger.Repetition.Duration
$Duration = $Duration -replace "PT"
$Duration = $Duration -replace "P"
$Duration = $Duration -replace "H", " Hours"
$Duration = $Duration -replace "D", " Days"
$Duration = $Duration -replace "M", " Minutes"
$Duration = "for " + $Duration
}
Else
{
$Duration="Indefinitely"
}
}
if($xml.task.Triggers.CalendarTrigger.ChildNodes.name.Contains("ScheduleByDay"))
{
$daysinterval = $xml.task.Triggers.CalendarTrigger.ScheduleByDay.DaysInterval + " days"
$daysinterval = $daysinterval -replace "1 days", "day"
$trigger = "At " + $StartBoundary[1] + " every " + $daysinterval
if($interval)
{
$trigger += " - After triggered repeat every " + $Interval + " for a duration of " + $Duration
}
}
Elseif($xml.task.Triggers.CalendarTrigger.ChildNodes.name.Contains("ScheduleByWeek"))
{
$weeksinterval = $xml.task.Triggers.CalendarTrigger.ScheduleByWeek.WeeksInterval + " weeks"
$weeksinterval = $weeksinterval -replace "1 weeks", "week"
$dayarray = $xml.task.Triggers.CalendarTrigger.ScheduleByWeek.DaysOfWeek.ChildNodes.name
if($dayarray[0].count -gt 1)
{
for($i=0;$i -lt $dayarray.count;$i++)
{
if($i -eq 0 -or $i -eq ($dayarray.count-1))
{
$days += $dayarray[$i]
}
else
{
$days += ", " + $dayarray[$i]
}
}
}
else
{
$days = $dayarray
}
$trigger = "At " + $StartBoundary[1] + " on " + $days + " every " + $weeksinterval + ", starting " + $StartBoundary[0]
if($interval)
{
$trigger += " - After triggered repeat every " + $Interval + " for a duration of " + $Duration
}
}
Elseif($xml.task.Triggers.CalendarTrigger.ChildNodes.name.Contains("ScheduleByMonth") -and -not($xml.task.Triggers.CalendarTrigger.ChildNodes.name.Contains("ScheduleByMonthDaysOfWeek")))
{
$dayarray = $xml.task.Triggers.CalendarTrigger.ScheduleByMonth.DaysOfMonth.Day
$montharray = $xml.task.Triggers.CalendarTrigger.ScheduleByMonth.months.childnodes.name
for($i=0;$i -lt $dayarray.count;$i++)
{
if($i -eq 0 -or $i -eq ($dayarray.count-1))
{
$days += $dayarray[$i]
}
else
{
$days += ", " + $dayarray[$i]
}
}
If($montharray[0].count -gt "1")
{
for($i=0;$i -lt $montharray.count;$i++)
{
if($i -eq 0 -or $i -eq ($montharray.count-1))
{
$months += $montharray[$i]
}
else
{
$months += ", " + $montharray[$i]
}
}
}
else
{
$months = $montharray
}
$trigger = "At " + $StartBoundary[1] + " on day " + $days + " of " + $months + " starting " + $StartBoundary[0]
if($interval)
{
$trigger += " - After triggered repeat every " + $Interval + " for a duration of " + $Duration
}
}
Elseif($xml.task.Triggers.CalendarTrigger.ChildNodes.name.Contains("ScheduleByMonthDayOfWeek"))
{
$weekarray = $xml.task.Triggers.CalendarTrigger.ScheduleByMonthDayOfWeek.weeks.week
$dayarray = $xml.task.Triggers.CalendarTrigger.ScheduleByMonthDayOfWeek.DaysOfWeek.childnodes.name
$montharray = $xml.task.Triggers.CalendarTrigger.ScheduleByMonthDayOfWeek.months.childnodes.name
for($i=0;$i -lt $weekarray.count;$i++)
{
if($i -eq 0 -or $i -eq ($weekarray.count-1))
{
$weeks += $weekarray[$i]
}
else
{
$weeks += ", " + $weekarray[$i]
}
}
$weeks = $weeks -replace "1","First"
$weeks = $weeks -replace "2","Second"
$weeks = $weeks -replace "3","Third"
$weeks = $weeks -replace "4","Fourth"
if($dayarray[0].count -gt 1)
{
for($i=0;$i -lt $dayarray.count;$i++)
{
if($i -eq 0 -or $i -eq ($dayarray.count-1))
{
$days += $dayarray[$i]
}
else
{
$days += ", " + $dayarray[$i]
}
}
}
else
{
$days = $dayarray
}
If($montharray[0].count -gt "1")
{
for($i=0;$i -lt $montharray.count;$i++)
{
if($i -eq 0 -or $i -eq ($montharray.count-1))
{
$months += $montharray[$i]
}
else
{
$months += ", " + $montharray[$i]
}
}
}
else
{
$months = $montharray
}
}
}
elseif($triggerType -eq "TimeTrigger")
{
$StartBoundary = $xml.task.Triggers.TimeTrigger.StartBoundary
$StartBoundary = $StartBoundary.Split("T")
if($xml.task.Triggers.TimeTrigger.ChildNodes.name.Contains("Repetition"))
{
$Interval = $xml.task.Triggers.TimeTrigger.Repetition.Interval
$Interval = $Interval -replace "PT"
$Interval = $Interval -replace "H", " Hours"
$Interval = $Interval -replace "D", " Days"
$Interval = $Interval -replace "M", " Minutes"
$Interval = " Repeat every " + $Interval
if($xml.task.Triggers.TimeTrigger.Repetition.ChildNodes.name.Contains("Duration"))
{
$Duration = $xml.task.Triggers.CalendarTrigger.Repetition.Duration
$Duration = $Duration -replace "PT"
$Duration = $Duration -replace "H", " Hours"
$Duration = $Duration -replace "D", " Days"
$Duration = $Duration -replace "M", " Minutes"
$Duration = "for " + $Duration
}
Else
{
$Duration="Indefinitely"
}
}
$trigger = "At " + $StartBoundary[1] + " on " + $StartBoundary[0]
if($interval)
{
$trigger += " - After triggered repeat every " + $Interval + " for a duration of " + $Duration
}
}
else
{
$trigger=$triggerType
}
$object2 = New-Object system.object
$object2 | add-member -type NoteProperty -name Name -Value $task.name
#$object2 | add-member -type NoteProperty -name Path -Value $task.path
#$object2 | add-member -type NoteProperty -name LastRunTime -Value $task.lastruntime
#$object2 | add-member -type NoteProperty -name LastTaskResult -Value $task.LastTaskResult
#$object2 | add-member -type NoteProperty -name State -Value $task.state
$object2 | add-member -type NoteProperty -name RunAs -Value ($task | where {$_.runas -ne $null} | foreach-object {$objSID2 = New-Object System.Security.Principal.SecurityIdentifier ($_.runas)
$objUser2 = $objSID.Translate( [System.Security.Principal.NTAccount])
$objuser2.value})
$object2 | add-member -type NoteProperty -name Command -Value $task.command
$object2 | add-member -type NoteProperty -name Arguments -Value $task.arguments
$object2 | add-member -type NoteProperty -name Triggers -Value $trigger
$object2 | add-member -type NoteProperty -name Server -Value $task.server
#$object2 | add-member -type NoteProperty -name TimesFailed -Value $null
#$object2 | add-member -type NoteProperty -name MsgSent -Value $null
if($object2.name -notlike "Adobe*" -and $object2.name -notlike "Optimize Start Menu*" -and $object2.name -notlike "GoogleUpdate*")
{
$taskreport += $object2
}
}
}
}
}
}
#Check each task in the array for failure
foreach($task in $taskarray)
{
#Check to see if failed ignoring never run and currently running
if(($task.LastTaskResult -ne 0) -and ($task.LastTaskResult -ne 267011) -and ($task.LastTaskResult -ne 267009) -and ($task.State -ne 4))
{
$failedTasks += $task
}
}
#If there are failed tasks update previous failed task report and create message based on threshold and whether a message has already been sent
if($failedTasks.count -gt 0)
{
#Generate an alert message to send
foreach($task in $failedTasks)
{
if($previousFailedTasks.name -contains $task.name)
{
$index = [array]::indexof($previousFailedTasks.name,$task.name)
if($task.LastRunTime -ne $previousFailedTasks[$index].LastRunTime)
{
$task.TimesFailed = ($previousFailedTasks[$index].TimesFailed -as [int]) + 1
$task.MsgSent = $previousFailedTasks[$index].MsgSent
$task.ShutdownStateCount = $previousFailedTasks[$index].ShutdownStateCount
}
else
{
$task.TimesFailed = $previousFailedTasks[$index].TimesFailed
$task.MsgSent = $previousFailedTasks[$index].MsgSent
$task.ShutdownStateCount = $previousFailedTasks[$index].ShutdownStateCount
}
}
else
{
$task.TimesFailed = "1"
}
if($task.LastTaskResult -eq -2147023781)
{
$task.ShutdownStateCount += 1
}
if(($task.ShutdownStateCount % 6) -eq 1)
{
$shutdownMsg += $task.name + " " + $task.path + " on " + $task.server + " is in System Shutdown in Progress state." + "<br>`n"
}
if($threshold.taskname -contains $task.name)
{
$thresholdindex = [array]::indexof($threshold.taskname,$task.name)
if($task.TimesFailed -ge $threshold[$thresholdindex].Threshold)
{
if($task.MsgSent -ne $true)
{
$msg += $task.name + " " + $task.path +" failed on " + $task.server + " at " + $task.LastRunTime + "<br>`n"
$task.MsgSent = $true
}
}
Else
{
$task.msgsent = $false
}
}
Elseif($task.MsgSent -ne $true)
{
$msg += $task.name + " " + $task.path +" failed on " + $task.server + " at " + $task.LastRunTime + "<br>`n"
$task.msgsent = $true
}
}
}
#Create and save report of failed tasks
$failedTasks | Export-Csv "c:\scripts\ScheduledTaskCheck\failedtaskreport.csv" -NoTypeInformation
#Create and save report of tasks
$taskreport | Export-CSV "c:\scripts\ScheduledTaskCheck\taskreport.csv" -NoTypeInformation
#Send message if there is one to send
if($msg -ne $null)
{
send-mailmessage -From "[email protected]" -to @("[email protected]", "[email protected]") -subject "Scheduled Task(s) Failed" -BodyAsHtml $msg -smtpserver "smtpserver.domain.com"
}
if($shutdownMsg -ne $null)
{
send-mailmessage -From "[email protected]" -to @("[email protected]", "[email protected]") -subject "Scheduled Task(s) in System Shutdown in Progress State" -BodyAsHtml $msg -smtpserver "smtpserver.domain.com"
}