Real Time Service Monitoring with vbscript

Service monitoring sometimes become inevitable for any server admin. Here is a script to keep watching a windows service for any change in status. The script will alert you as soon as a service shuts down or starts up with no latency using minimal resources. The sample script here is to monitor sql server related services. You could alter the text pattern as marked to monitor your own service. Save the script to a vbs file and name it like For eg.”ServiceMonitoring.vbs” and double click the file to execute. The script keeps running in the background scanning the service status and sends out HTML email alert if it finds any change in the specified service status.

' Monitor Changes in Service Status
' By Sherbaz Mohamed, ceo@splitexpense.in
' www.sherbaz.com
' March 16 2015
' ..........................................
' Provide Server name, smtp server url, from address and to address
strComputer = "."
smtpsvr = "inrelaymail.sherbaz.com"
fromEmail = "Sherbaz Mohamed "
toEmail = "mail@sherbaz.com"

Set objRE = New RegExp

With objRE
	.Pattern    = "sql" ' -- Change this pattern text to match the service name to be monitored
	.IgnoreCase = True
	.Global     = False
End With

' -----------------------------------------
' #### Code starts Here ### No need to change any values below

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colServices = objWMIService. _ 
    ExecNotificationQuery("Select * from __instancemodificationevent " _ 
        & "within 30 where TargetInstance isa 'Win32_Service'")
i = 0

Do While i = 0
    Set objService = colServices.NextEvent
    If objService.TargetInstance.State <> _ 
        objService.PreviousInstance.State Then
        	If objRE.Test(objService.TargetInstance.Name) Then
		        'Wscript.Echo objService.TargetInstance.Name _ 
		         '   &  " is " & objService.TargetInstance.State _
		          '      & ". The service previously was " & _
		           '         objService.PreviousInstance.State & "."
		           	Set objEmail = CreateObject("CDO.Message")

					objEmail.From = fromEmail
					objEmail.To = toEmail
					objEmail.Subject = objService.TargetInstance.Name & " is " & objService.TargetInstance.State 
					objEmail.HTMLbody = "

Service Monitoring

" & _ "" & _ objService.TargetInstance.Name & " is not " & objService.PreviousInstance.State & " anymore." & _ "


" & _ "
www.sherbaz.com
" objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtpsvr objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 objEmail.Configuration.Fields.Update objEmail.Send End if End If Loop

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.