Help us understand the problem. What is going on with this article?

PowerShellでサーバーの死活監視

More than 1 year has passed since last update.

監視対象に定期的にPingを打って反応なければメールを送信するスクリプトです。
イベントログにも記録します。

Check-DeadOrAlive.ps1

# 監視対象
[String[]]$addressAp = @('ホスト1','ホスト2',...)

# 間隔
$interleave=180

# イベントログソース
$eventLogSource = "DeadOrAlive"


# メール送信
function Send-Mail( $Subject, $Body ) {
    $MailSv = "メールサーバー"
    $Port = 587
    $Encode = "UTF8"
    $address = "メールアドレス"

    $pwd = "パスワード" | ConvertTo-SecureString -AsPlainText -Force
    $cred = New-Object System.Management.Automation.PSCredential $address,$pwd

    Send-MailMessage `
        -To $address `
        -From $address `
        -SmtpServer $MailSv `
        -Credential $cred `
        -Encoding "UTF8" `
        -Port $Port `
        -Subject $Subject `
        -Body $Body 
}

# イベントログソース作成
if ([System.Diagnostics.EventLog]::SourceExists($eventLogSource) -eq $false){
    New-EventLog -LogName Application -Source $eventLogSource
}


$dead_or_alive = @{}
for($i = 0; $i -lt $addressAp.Count; $i++) {
    $dead_or_alive.Add($addressAp[$i],'alive')
}

# ping 
while(1){
    for($i = 0; $i -lt $addressAp.Count; $i++) {
        # Pingを実行します。
        $pingAlive = @(Test-Connection -ComputerName $addressAp[$i] -Quiet)

        if ($pingAlive -eq $True) {
            $message = "Check-DeadOrAlive SUCCESS:" + $addressAp[$i]
            echo $message
            Write-EventLog -LogName Application -Source $eventLogSource -EventId 1 -Message $message
            $dead_or_alive[$addressAp[$i]] = 'alive'
        } else {
            if($dead_or_alive[$addressAp[$i]] -eq 'alive'){
                # ログを記録する
                $message = "Check-DeadOrAlive ERROR:" + $addressAp[$i]
                echo $message
                Write-EventLog -LogName Application -Source $eventLogSource -EventId 1 -Message $message
                # メールを送信する
                $subject = $addressAp[$i] + " IS DEAD"
                [String]$date = Get-Date
                $body = $date + "`r`n" + $subject + "`r`nfrom ad.vanpool.lan"
                Send-Mail $subject $body
                $dead_or_alive[$addressAp[$i]] = 'dead'
            }
        }
    }


    # 待機
    Start-Sleep -s $interleave
}

# 終了
Write-EventLog -LogName Application -Source $eventLogSource -EventId 1 -Message "Check-DeadOrAlive: Terminated"

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away