特定计划任务无法运行时如何发送电子邮件 [英] How to send email when SPECIFIC scheduled task fails to run

查看:103
本文介绍了特定计划任务无法运行时如何发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Windows 2008 上的任务计划程序每天都会执行一个 exe 文件.如果该脚本无法启动,或者脚本在执行过程中失败,我希望收到电子邮件通知.有许多示例可以让 Task Schedular 根据事件日志条目发送电子邮件.但是,我只想在我的特定计划任务失败时收到通知,而不是收到所有以 EventID 203/103/201 失败的任务的通知.如果没有任何自定义软件,我怎么能做到这一点?

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?

推荐答案

创建一个运行此 PowerShell 脚本的新任务.

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
}

这篇关于特定计划任务无法运行时如何发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆