Wednesday, January 18, 2017

Quick agent health check script

A long long time ago in a life far far away, I wrote a quick and dirty agent health check script that allowed me to keep an eye on the unhealthy agents in my environments. I updated it over the years, but always kept it as VBScript, which is obviously now a little out of date, since everyone wants to use the far more posh PowerShell. So, here is a PS version.

Update the highlighted bits, save as a ps1 file and be sure to test in your lab before using in production. Script provided without guarantees.

##############################################################################
#
#   SCOM-Agent-healthCheckscript.ps1
#
#    This script retrieves all unhealthy agents from OpsMgr, and pings them.
#
##############################################################################

# Variables

$FromEmail = "<from email address>"
$ToEmail = "<recipient email address>"
$MailServer = "<mail server>"

$ReportDate = Get-Date -format "yyyy-M-dd"

# there should be no need to update the script beyond this point

# Open the content
#$body = @()

$body = "<table><tr><td><b>Server Name</b></td><td><b>Ping Response</b></td></tr>"

# Connect to Operations Manager

Import-module OperationsManager

# Fetch the agent information
$AgentClass = get-SCOMClass -name "Microsoft.SystemCenter.Agent"
$Agents = Get-SCOMMonitoringObject -class:$AgentClass | where {$_.IsAvailable -ne "Success"}

# Set the counters to Zero
$n = 0
$i = 0

# Loop through the unhealthy agents and ping them
foreach ($Agent in $Agents) {
$n = $n+1

   if (test-Connection -ComputerName $Agent -Count 2 -Quiet )
        {
    $Status = "Responds"
         }
         else
         {
      $Status = "Unreachable"
      $i = $i+1
         }

# Status update
Write-Host "$Agent checked"

# Write to the report
$ReportOutput = "<tr><td>$Agent</td><td>$Status</td></tr>"
$body += $ReportOutput
}

$body += "</table>"

# Write-Host "There are $n agents in total and $i not pinging"

$mbody = "<p>There are <b>$n</b> agents in total and <b>$i</b> not pinging</p> $body"


Write-Host “Sending Email”

#Creating a Mail object
     $msg = new-object Net.Mail.MailMessage
    
#Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($mailserver)

#Email structure
$Subject = "SCOM Agent Health Check - $ReportDate"

     $msg.From = $FromEmail
     $msg.ReplyTo = $FromEmail
     $msg.To.Add($ToEmail)
     $msg.subject = $Subject
     $msg.IsBodyHtml = $true
     $msg.body = $mbody

  #Sending email
    $smtp.Send($msg)

#write-host "Email sent"

No comments:

Related Posts with Thumbnails