因为Win 2008 R2服务器上面有很多计划任务,邮件通知如果任务运行失败。因为任务运行失败会有不同的Event ID生成是日志里面,所以,如果有不同的Event ID,应该再做一个计划任务。

  新建一个计划任务,类型如下,并设置做以下三个配置.

  • 选择Run whether user is logged on or not.

  • Triggers配置如下图.

    wKioL1VmiWDSa0HBAAG-JPUukdo982.jpg

  • Action 配置如下.

    Program script C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe


  • Add arguments (optional) -command "C:\scripts\Task_Failed_Alert.ps1"wKiom1VmiFSD6rzyAAD9B83DCVA499.jpg

Task_Failed_Alert.ps1 脚本如下。

#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

wKioL1VmlIDAIWt4AAFzbu3Vz2U507.jpg

可以新建一个任务来测试以上邮件通知是否成功,以权限不够的用户来运行这个任务,就可以产生Event ID 101的错误。

注意,不要设置默认记事本打开这个脚本,否则任务运行时就会以记事本来打开这个脚本,而不是PowerShell.exe来运行。