因为Win 2008 R2服务器上面有很多计划任务,邮件通知如果任务运行失败。因为任务运行失败会有不同的Event ID生成是日志里面,所以,如果有不同的Event ID,应该再做一个计划任务。
新建一个计划任务,类型如下,并设置做以下三个配置. Task_Failed_Alert.ps1 脚本如下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| #This is script is for email alert when Event ID 101 occur in Task Scheduler.
$OutputFileLocation = "C:\scripts\Task_Failed_Alert.log"
Start-Transcript -path $OutputFileLocation -append
$ErrorMessage = wevtutil qe Microsoft-Windows-TaskScheduler/Operational "/q:*[System [(EventID=101)]]" /f:text /rd:true /c:1 #Get EventID 101 lastest details in Operational log
$ComputerName = $ErrorMessage |select-string -pattern "computer" #Display specific line.
$ComputerNames = $ComputerName.Line.Split(".")| Select-Object -first 1 #Split specific phrase.
$ErrorSubject = $ErrorMessage |Select-string -pattern "Additional Data" #Display specific line.
$ErrorSubjects = $ErrorSubject.Line.Split(".")| Select-Object -first 1 #Split specific phrase.
$ErrorSub = "$Computernames" + " " + "$ErrorSubjects"
$ErrorMessage = $ErrorMessage |Out-String #Formatting string for email Body.
Send-MailMessage -From "ABC@ABC.com" -To "BBC@ABC.com" -Subject "$ErrorSub" -Body "$ErrorMessage" -SMTPServer SMTPSERVER
Write-Host "Mail message sent on $(Get-Date -format 's')"
Write-Host $ErrorMessage
|
可以新建一个任务来测试以上邮件通知是否成功,以权限不够的用户来运行这个任务,就可以产生Event ID 101的错误。
注意,不要设置默认记事本打开这个脚本,否则任务运行时就会以记事本来打开这个脚本,而不是PowerShell.exe来运行。
|