How to send email when SPECIFIC scheduled task fails to run

冷暖自知 提交于 2019-12-23 21:26:34

问题


I have a exe file that is executed every day by the Task Scheduler on my Windows 2008. If that script should fail to start, or if the script fails during execution, I would like to get an email notification. There are many examples of getting Task Schedular to send an email based on an event log entry. However, I only want to be notified if MY particular scheduled task fails, not get a notification for all tasks that fails with an EventID 203/103/201. How can I do that without any custom software?


回答1:


Create a new Task that runs this PowerShell Script.

$ScheduledTaskName = "Taskname"
$Result = (schtasks /query /FO LIST /V /TN $ScheduledTaskName  | findstr "Result")
$Result = $Result.substring(12)
$Code = $Result.trim()

If ($Code -gt 0) {
    $User = "admin@company.com"
    $Pass = ConvertTo-SecureString -String "myPassword" -AsPlainText -Force
    $Cred = New-Object System.Management.Automation.PSCredential $User, $Pass


$From = "Alert Scheduled Task <task@servername>"
$To = "Admin <admin@company.com>"
$Subject = "Scheduled task 'Taskname' failed on SRV-001"
$Body = "Error code: $Code"
$SMTPServer = "smtp.company.com"
$SMTPPort = "25"

Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $Cred
}


来源:https://stackoverflow.com/questions/40386280/how-to-send-email-when-specific-scheduled-task-fails-to-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!