LoginSignup
1
3

More than 5 years have passed since last update.

PowerShellスクリプトによるメール送信

Last updated at Posted at 2017-03-17

PowerShellを急に触ることになったヒトのための備忘録、第二弾。

第一弾:ロギング編
http://qiita.com/yoshifuji/items/c94e3a8e5c2229f370af

Winサーバ上でPowerShellスクリプトエラーを検知したら、メールサーバ経由でメール送信できるようにしたい。

環境

WindowsServer2012 R2

定義する

下記のようなスクリプトを書いて、デスクトップに mail.ps1 といった名前で保存する。

## HOWTO USE
## 1.IMPORT FILE BELOW 
# . ".\\mail.ps1"
## 2.CALL FUNCTION 
# MailSendLog "dummy_batch_id" "dummy_survey_id" "dummy_error"

$to = "system@your-domain.com"
$from = "apps-" + [Net.Dns]::GetHostName() + "@your-domain.com"
$smtp = "172.21.xxx.xxx" #YOUR MAIL SERVER
$subject = "APP ERROR OCCURRED in dev-" + [Net.Dns]::GetHostName()

$now = Get-Date    
$log = "{0:0000}-{1:00}-{2:00} " -f $now.Year, $now.Month, $now.Day
$log += "{0:00}:{1:00}:{2:00} " -f $now.Hour, $now.Minute, $now.Second

function MailSendLog($batch_id, $survey_id, $error){
    $body =
@"
batch_id = $batch_id
app_id = $app_id
error = $error
log = $log
"@

    Send-MailMessage -To $to -From $from -SmtpServer $smtp -Subject $subject -Body $body -Encoding UTF8
    Return $log
}

呼び出す

要領は第一弾と同様。

. D:/mappshulft/batch/mail.ps1

try {
    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
    Invoke-RestMethod -Method Post -Uri $uri -Body $body -Headers @{"Content-Type"="application/json"}
} catch {
    echo '$error[0] = ' + $error[0]
    MailSendLog "F_LOGIC01" $survey_id $error[0] #メール送信実行部
}
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3