Task Scheduler設定排程錯誤時發送Mail - Powershell

Posted by: Max Chen | in Powershell | 1 year ago |

發送排程錯誤mail腳本

首先是要執行的腳本,依照需求改成你要的:

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

#encript password to secret.txt at first time
#Read-Host "Password" -AsSecureString | ConvertFrom-SecureString | Set-Content "E:\MaxChen\Secret.txt"
If ($Code -gt 0) {
    $Cred = New-Object System.Management.Automation.PSCredential ("xxxx@gmail.com", (Get-Content "E:\MaxChen\Secret.txt" | ConvertTo-SecureString))
################################################################################

$From = "yyyy@gmail.com"
[string[]]$To = "xxx1@gmail.com","xxx@gmail.com"
$Subject = "Job Fail"
$Body = "Error code: $Code"
$SMTPServer = "xxxx.xx.com"
$SMTPPort = "25"

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

註:執行時記得先存一次密碼到Secret.txt(把#encript password to secret.txt at first time下面那段註解打開),每台電腦key不同,所以每一台電腦執行時都要重新輸入一次。

排程設定方法

1. Trigger

設定如下,只要Task Schduler有出現event : 203(代表排程出錯),就會觸發:

image

2. Action

如同一般執行ps1腳本一樣,引入上面的腳本:

image

註:send an email已棄用

image

3. 測試

以上設定都沒問題的話,你就會收到email拉!

image

Reference:

https://stackoverflow.com/questions/10241816/powershell-send-mailmessage-email-to-multiple-recipients

https://o365reports.com/2019/08/02/schedule-powershell-script-task-scheduler/

https://blog.darkthread.net/blog/ps-secure-string/

https://superuser.com/questions/249103/make-windows-task-scheduler-alert-me-on-fail

https://stackoverflow.com/questions/496566/error-server-does-not-support-secure-connections

Currently unrated
 or 

Subscribe

* indicates required

Recent Posts

Archive

2023
2022
2021

Categories

Apache 1

Data Science 2

Dbfit 1

Design Pattern 1

Devops 4

DigitalOcean 1

Django 1

English 3

Excel 5

FUN 4

Flask 3

Git 1

HackMD 1

Heroku 1

Html/Css 1

Linux 4

MDX 1

Machine Learning 2

Manufacture 1

Master Data Service 1

Mezzanine 18

Oracle 1

Postgresql 7

PowerBI 4

Powershell 4

Python 22

SEO 2

SQL Server 53

SQL Server Analytics Service 1

SQLite 1

Windows 1

database 8

work-experience 1

其他 1

投資入門 1

投資心得 2

時間管理 1

總體經濟 2

自我成長 3

資料工程 1

Tags

SEO(1) Github(2) Title Tag(2) ML(1) 李宏毅(1) SQL Server(18) Tempdb(1) SSMS(1) Windows(1) 自我成長(2) Excel(1) python Flask(1) python(5) Flask(2)

Authors

Max Chen (159)

Feeds

RSS / Atom

Task Scheduler設定排程錯誤時發送Mail - Powershell

© COPYRIGHT 2011-2022. Max的文藝復興. ALL RIGHT RESERVED.