Friday, November 14, 2014

Powershell script to checking event viewer for exceptions remotely then send email and restart the windows service.

Powershell script for checking any specific file or event viewer for exceptions remotely then send email and restart the windows service.
===============================================================================================================================

This script is for Checking "OutOfMemoryException" or any type of exception in the windows server/machine and then it will send email notification and then restart the respective service.
example: In our case, we have a old service program, which is running on windows and we haven't source code of this one. so after running few days it is stopped by ourofmemory exception. sometime we couldn't know when it was stopped how many days it was stopped. but it should run 24/7 hours.
         so after geting informed that it is not running then someone needs to start it manually. (it is also a problem at night or weekend time). so i wrote this script and it solved our problem. but now we are trying to build a new one. it will take time.



1) create a powershell script (.ps1) file with this follwing code like,  script_for_outofmemory.ps1


=============================================================================================================================================================
 #### For Checking in the event viewer of windows for "OutOfMemoryException"  
 $a = Get-EventLog -LogName "Application" -computername remote_machine_name -After (Get-Date).AddMinutes("-30") | Where-Object {$_.Source-like "*ExceptionManagerPublishedException*"} | Where-Object {$_.EntryType-eq "Error"} | Where-Object {$_.Message -like "*OutOfMemoryException*"}  
 #### following line is for Checking in a specific file of windows for "OutOfMemoryException"  
#### $a = Get-Content -Path \\machine_name\d$\ErrorLog\log.txt | Select-String System.OutOfMemoryException  
  if ($a -ne $Null)  
   {  
     "OutOfMemoryException is found in log.txt within 60 minutes and checking for restart"  
     #-----checking for re-start within 30 minutes begin----  
     $r = Get-EventLog -LogName "Application" -computername machine_name -After (Get-Date).AddMinutes("-30") |Where-Object {$_.Source-like "*TomcatService*"} | Where-Object {$_.EntryType-eq "Information"} | Where-Object {$_.Message -like "*Service Start*"}  
        if ($r -ne $Null)  
           {  
             "Restart found within 30 minutes, Tomcat Service is restarted by someone"  
           }  
       ELSE  
           {  
               "Restart not found, Sending email tomcat service needs to be Restarted"  
               ## email sending----------------  
               $emailFrom = "Halim@test.com"  
               # Use commas for multiple addresses  
               $emailTo = "user1@test.com,user2@test.com"  
               $subject = "(Tomcat Auto-restart script) Tomcat service needs to be Restarted"  
               $body = "(Tomcat Auto-restart script): Cause: The Tomcat server encountered System Out of Memory Exception in errlog.txt. This exception can be seen in \\machine_name\d$\ErrorLog\log.txt"  
               $smtpServer = "smtp_server_ip_or_name"  
               $smtp = new-object Net.Mail.SmtpClient($smtpServer)  
               $smtp.Send($emailFrom, $emailTo, $subject, $body)   
               #----checking service status then stop and start begin  
               #-------------------------------------------------------------------------------------------------  
               "Checking status of TomcatDocumentService....."  
               $s=get-service -Name TomcatDocumentService -ComputerName Machine_name_Tomcat  
               $s.Status  
                 if ($s.Status -eq 'Stopped')  
                   {  
                   "found TomcatDocumentService Service is stopped"  
                ############ Service start command   
                   Get-Service -Name TomcatDocumentService -ComputerName Machine_name_Tomcat | Set-Service -Status Running  
                     ## email sending----------------  
                   $emailFrom = "Halim@test.com"  
                   # Use commas for multiple addresses  
                   $emailTo = "user1@test.com,user2@test.com"  
                   $subject = "(Tomcat Auto-restart script) Tomcat service has been Restarted Successfully"  
                   $body = "(Tomcat Auto-restart script): Cause: The Tomcat server encountered System Out of Memory Exception in errlog.txt. This exception can be seen in \\machine_name\d$\ErrorLog\log.txt. Please Check and take appropriate action manually!."  
                   $smtpServer = "smtp_server_ip_or_name"  
                   $smtp = new-object Net.Mail.SmtpClient($smtpServer)  
                   $smtp.Send($emailFrom, $emailTo, $subject, $body)   
                   }  
                 ELSE  
                    {  
                   "Found TomcatDocumentService service is running "  
                ############ Service stop command   
                  Get-Service -Name TomcatDocumentService -ComputerName Machine_name_Tomcat | Set-Service -Status Stopped  
                   #---------wait 2 minutes and check status begin  
                   "Waiting 8 minutes......start point "  
                   Start-Sleep -Seconds 480 #---wait 8 minutes  
                   "Waiting 8 minutes......end point "  
                   #-----------------------------again check status begin  
                   "Re-checking service TomcatDocumentService...."  
                       $ss=get-service -Name TomcatDocumentService -ComputerName Machine_name_Tomcat  
                        $ss.Status  
                       if ($ss.Status -eq 'Stopped')  
                         {  
                         "TomcatDocumentService service found stopped in re-check"  
                ############ Service start command   
                     Get-Service -Name TomcatDocumentService -ComputerName Machine_name_Tomcat | Set-Service -Status Running  
                         ## email sending----------------  
                     $emailFrom = "Halim@test.com"  
                     # Use commas for multiple addresses  
                    $emailTo = "user1@test.com,user2@test.com"  
                         $subject = "(Tomcat Auto-restart script) Tomcat service has been Restarted Successfully"  
                         $body = "(Tomcat Auto-restart script): Cause: The Tomcat server encountered System Out of Memory Exception in errlog.txt. This exception can be seen in \\machine_name\d$\ErrorLog\log.txt. Please Check and take appropriate action manually!."  
                         $smtpServer = "smtp_server_ip_or_name"  
                         $smtp = new-object Net.Mail.SmtpClient($smtpServer)  
                         $smtp.Send($emailFrom, $emailTo, $subject, $body)   
                         }  
                       ELSE  
                         {  
                          ## email sending----------------  
                     $emailFrom = "Halim@test.com"  
                     # Use commas for multiple addresses  
                     $emailTo = "user1@test.com,user2@test.com"  
                         $subject = "(Restart script) Tomcat service needs to be restarted, but the script could not stop the process. Pls. check and take appropriate action manually."  
                         $body = "(Tomcat Auto-restart script): The Tomcat server encountered System Out of Memory Exception in errlog.txt. This exception can be seen in \\machine_name\d$\ErrorLog\log.txt. Please check and take necessary action as soon as possible."  
                         $smtpServer = "smtp_server_ip_or_name"  
                         $smtp = new-object Net.Mail.SmtpClient($smtpServer)  
                         $smtp.Send($emailFrom, $emailTo, $subject, $body)   
                         }  
                     }  
             }  
 }  
 ELSE  
 {  
  "Tomcat is running fine"  
 }  

=========================================================================================================================================================


2) Create a schedule job with you desire interval via passing below action parameter
  Note: create the job with privileage user (execute as a different user).


Powershell.exe -executionpolicy remotesigned -File C:\halim_documents\script_for_outofmemory.ps1


note: (For invoking windows powershell.exe from remote machine and with different user, you can {press shift + right click on windows powershell.exe} then click on "run as diferent user" put user_name and password