Powershellでイベントログを監視してサービスを再起動する
2024年10月15日
今の会社に来てからWindowsサーバが多いのでWindows関連が多いです。
Table of Contents
Toggle設定
- 15分おきにタスクスケジューラを起動
- Powershellで期間内の特定のイベントIDを取得
- もしWarningのログがあればServiceを再起動
- 念のためメールを送る
Powershellスクリプト中身
利用環境に合わせてFrom、Toアドレス、SERVICE_NAME、EVENT_IDを変更して.ps1ファイルを作成。SMTPサーバが環境内になければメール送信部分を消してください。
# Settings
$From = "from@example.com"
$time = Get-Date -DisplayHint Time
$To = "to@example.com"
$SMTPServer = "192.168.X.X"
$Port = "25"
$Service = "SERVICE_NAME"
$EventId = "EVENT_ID"
# Check Event log ID within 15 mins
$EventLogs = Get-EventLog -LogName Application -InstanceId $EventId -EntryType Warning -after (Get-Date).AddMinutes(-15) | FT TimeGenerated, InstanceID, Message -AutoSize
# Restart the service and send an email
If ($null -ne $EventLogs) {
Restart-Service -Name $Service
# Send an email
$Subject="Service " + $Service + " restarted at " + $time
$body = "Event Log ID " + $EventId + " with Warning detected. Restarted the service."
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer,$Port)
$SMTPClient.EnableSsl=$false
$MailMassage = New-Object Net.Mail.MailMessage($From,$To,$Subject,$body)
$SMTPClient.Send($MailMassage)
}
# Check the service state
while ((Get-Service $Service).Status -eq 'Stopped')
{
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
}
タスクスケジューラ登録
トリガー
15分おきに繰り返すように設定。間隔は好みに合わせて変えてください。
操作
- プログラム/スクリプト(Program/script)
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
- 引数の追加(Add arguments)
作成したスクリプトを指定。
-ExecutionPolicy Bypass -File "C:\Scripts\MonitorEventLogs.ps1"
おわり
最近はスクリプトを公開するだけの記事が多いですが・・この記事が誰かの役に立てばいいなと思います。