首先是要執行的腳本,依照需求改成你要的:
$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不同,所以每一台電腦執行時都要重新輸入一次。
設定如下,只要Task Schduler有出現event : 203(代表排程出錯),就會觸發:
如同一般執行ps1腳本一樣,引入上面的腳本:
註:send an email已棄用
以上設定都沒問題的話,你就會收到email拉!
Reference:
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
Share on Twitter Share on FacebookSQL Server Analytics Service 1
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)
Max Chen (159)