Submitted By: P. Sukus

Lists all the scheduled tasks on a set of servers that failed to execute in the past three days.

PowerShell
Edit|Remove
*****************Start Script********************
# schedulewrapper.ps1 - Scheduled Task Monitor
# Created by P. Sukus 
# Version 1.0 3/21/08
# Written for PowerShell 1.0
#
# Description:
# This script uses schtasks to get all the task information on every server defined in scheduletaskServers.txt 
# Poweshell is then used to parse the information down to tasks that executed in the last 3 days that have
# failed. Disabled Schedules for tasks are filtered out as well. This script then emails an html report of any failed 
# tasks
 
$Dateminus=(get-date (get-date).AddDays(-3) -f g)
 
$a = ""
 
$b = "<H2>Failed Scheduled Tasks since $Dateminus</H2>"
 
$c = 0
 
$sendemail = 0
#read the list of servers that have scheduled tasks on them to monitor
$Servers = Get-Content scheduletaskServers.txt
$servercount = 0
$Body = ""
foreach ($svr in $Servers){
                # EXAMPLE: schtasks /query /FO CSV /V > ScheduleTaskMon.log
                If ($servercount -gt 0) {
                                #write-host schtasks /query /s $svr /FO CSV /NH /v >> ScheduleTaskMon.csv
                                schtasks /query /s $svr /FO CSV /NH /v >> ScheduleTaskMon.csv
                                }
                Else {
                                #write-host schtasks /query /s $svr /FO CSV /v > ScheduleTaskMon.csv
                                schtasks /query /s $svr /FO CSV /v > ScheduleTaskMon.csv
                                }
                
                $servercount++
}
 
 
$errors = Import-Csv ScheduleTaskMon.csv | 
Where-Object {$_."Last Run Time" -lt $Dateminus -and $_."Schedule" -ne "Disabled" -and $_."Last Result" -ne 0}

$body = Import-Csv ScheduleTaskMon.csv | 
Where-Object {$_."Last Run Time" -lt $Dateminus -and $_."Schedule" -ne "Disabled" -and $_."Last Result" -ne 0} | 
select-object Hostname, Taskname, "Last Run Time", "Next run time", "Task to Run"| 
sort-object -property "Last Run Time" -descending | convertto-html -head $a -body $b

#change -and $_."Last Result" -eq 0} to -and $_."Last Result" -ne 0} in production in previous line
$c = $errors.count
                
If ($c -gt 0) {
                #Email the files that will deleted later in this script            
           
                $smtpServer = "SMTPSERVER"
                $mailer = new-object Net.Mail.SMTPclient($smtpserver)             
                $From = "Windows-Task-Scheduler@YOUR.NETWORK"
                $To = "ADMINS@YOUR.NETWORK"
                $subject = "$c Task Failures in the last 3 days"
                $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)  
                $msg.IsBodyHTML = $true
                $mailer.send($msg)
                }