在Windows Server 2012的Task Scheduler里面配置自動發送郵件


     最近在一台server上配置了每個周末備份數據庫的定時任務,想順手配置發送備份完成的郵件提醒我去Double Check一下備份結果。

悲劇地發現Send an email功能被新版的server給禁掉了。

只好另辟蹊徑,想到通過PowerShell腳本來發送也行,找到一個腳本:

############################################################################### ###########Define Variables######## $fromaddress = "donotreply@labtest.com" $toaddress = "Aishwarya.Rawat@labtest.com" $bccaddress = "Vikas.sukhija@labtest.com" $CCaddress = "Mahesh.Sharma@labtest.com" $Subject = "ACtion Required" $body = get-content .\content.htm $attachment = "C:\sendemail\test.txt" $smtpserver = "smtp.labtest.com" #################################### $message = new-object System.Net.Mail.MailMessage $message.From = $fromaddress $message.To.Add($toaddress) $message.CC.Add($CCaddress) $message.Bcc.Add($bccaddress) $message.IsBodyHtml = $True $message.Subject = $Subject $attach = new-object Net.Mail.Attachment($attachment) $message.Attachments.Add($attach) $message.body = $body $smtp = new-object Net.Mail.SmtpClient($smtpserver) $smtp.Send($message) #################################################################################

原文引自:Send HTML Email and attachment Powershell

然后,在Task Scheduler的任務里面,最后的位置添加一個Action,設置如下:

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

Arguments: -command "& 'C:\SendEmailScript\SendMail.ps1'" 

 

調試運行時發現還是有問題,在PowerShell里面運行,發現有錯誤日志:

xxx.ps1 cannot be loaded because the execution of scripts is disabled on this system.

 

原來Windows 2012 Server 默認是關閉腳本執行的,需要自己手動打開:

1. 以管理員身份運行PowerShell。

2. 檢查當前狀態:輸入 Get-ExecutionPolicy ,回車。 顯示: Restricted

3. 修改狀態:輸入 Set-ExecutionPolicy Unrestricted

4. 再次輸入 Get-ExecutionPolicy 檢查狀態應該顯示 Unrestricted

 

好了,至此,解決了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM