Powershell script that checks to see if the server is up

I setup a powershell script that runs on a schedule that pings the host in an interval. If there are no ping response, then the script sends email to the administrator alerting about the no ping response. For the ping, I used a command Test-Connection 

I also use a small text file to see if the email is already sent to an administrator. If the text file says “Sent”, then the ping test is not conducted. If the email is already sent, there’s no need to keep spamming the administrator. 

Here’s the code you can use.

$EmailSent = Get-Content c:\scripts\PowerStatus.ini
if ($EmailSent -ne "Sent")
  {
      if (Test-Connection ServerIPAddress -quiet)
         {
             echo "all Good"
             $reset = "All good"
              $reset | out-file c:\scripts\PowerStatus.ini
          } else
      {

           $EmailFrom = "notification@yourcompany.com"
           $EmailTo = "admin1@gmail.com,admin2@hotmail.com"
           $Subject = "Unable to connect to the Server"
           $Body = "Check to see if we are experiencing power outage"
           $SMTPServer = "smtp.gmail.com"
           $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
           $SMTPClient.EnableSsl = $true
           $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("userid", "password");
           $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
           $reset = "Sent"
           $reset | out-file c:\scripts\PowerStatus.ini
       }
}

Once the email has been sent, the PowerStatus.ini file will say “Sent” and you will need to reset the PowerStatus.ini file (either delete the file or you can modify the content of the PowerStatus.ini to anything but “Sent”).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s