Windowsログ内容をメール送信する

タスクスケジューラのイベントトリガーを利用してWindowsログ内容をメール送信してみます。

今回利用するのはWindowsのPowerShellを利用します。

事前に、PowerShellの実行権限設定を行ってください。

[スタート]->[すべてのプログラム]->[アクセサリ]->[Windows PowerShell](管理者権限で実行)

■ポリシーを変更する

PS C:\windows\system32> Set-ExecutionPolicy RemoteSigned

PS C:\windows\system32> Get-ExecutionPolicy RemoteSigned

PS C:\windows\system32>

■PowerShellスクリプトを用意(test.ps1)

#PowerShellでメール送信


    $username = "ore@hoge.com"

    $myhost = "192.168.0.160"

    $port = 25

    $from = "ore@hoge.com"

    $recipients = "ore@hoge.com"

    $subject = "server log info"

    $body = ""

# コマンド参考


#    $logArray = Get-EventLog -log System -InstanceId 1073748860 -Newest 1 | Format-List


    $logArray = Get-EventLog -log System -InstanceId 1073748860 -Newest 1


    $Index = [string] $logArray.Index

    $EntryType = [string] $logArray.EntryType

    $InstanceId = [string] $logArray.InstanceId

    $EventID = [string] $logArray.EventID

    $Source = [string] $logArray.Source

    $workMessage = [string]$logArray.Message

    $ReplacementStrings = [string]$logArray.ReplacementStrings


    $body = $EntryType +"`n"+ $EventID +"`n"+ $Source+"`n"+$workMessage+"`n"+$ReplacementStrings


    $sc = New-Object Net.Mail.SmtpClient

    $sc.Host = $myhost

    $sc.Port = $port

    $sc.Credentials = New-Object Net.NetworkCredential

    $sc.Credentials.UserName = $username

    $sc.send($from, $recipients, $subject, $body)

■タスクスケジューラーから起動するバッチファイルを作成(test.bat)


powershell C:\temp\test.ps1

■タスクスケジューラーに設定

トリガーイベントを設定し、操作でプログラムの開始を指定。

起動するプログラムは、test.bat

設定タブで「新しいインスタンスを並列で実行」にしておく。

コメントを残す

メールアドレスが公開されることはありません。

CAPTCHA