【powershell】Windows系統產生錯誤時,系統自動發送通知信

  • 1546
  • 0

 

Powershell程式碼如下

    $numbers = 1,2
    $mailbody = Get-WinEvent -FilterHashtable @{Logname='System'; level  = $numbers} | Select-Object -First 1
       $msg = "Time: " + ($mailbody | select -ExpandProperty TimeCreated)+ "`r`n" + "`r`n" +
              "Message: " + ($mailbody  | select -ExpandProperty Message) + "`r`n" + "`r`n" +
              "EventID: " + ($mailbody  | select -ExpandProperty ID)
    
    $mail = New-Object System.Net.Mail.MailMessage
    $CompName = (Get-Content Env:\COMPUTERNAME).ToString()
    #寄件人email
    $mail.From = (hostname) + "@abc.com"
    #收件人email,多收件人時分多行加入
    $mail.To.Add("test1@abc.com")
    #郵件標題
    $mail.Subject ="System Error Message"
    
    #郵件內文
    $mail.Body = $msg
    
    # create attachment / 插入附件
    #$att = New-Object System.Net.Mail.Attachment $logfile
    #$mail.Attachments.Add($att)
    
    #送郵件,要設定SNMP伺服器
    $smtp = New-Object System.Net.Mail.SmtpClient("192.168.0.1")
    $smtp.Send($mail) 

使用備份程式taskschd

1.建立觸發程序

2.呼叫powershell程式

3.收到通知信如下