Friday 2 February 2018

How to monitor a windows service using vb script

1. The below-mentioned script is to monitor on a window service.

The service name is 'W3SVC' (World Wide Web Publishing Service), you can change the service name as per your requirement. If the script finds the service is stopped then it will start the stopped service.
The below code is a loop which runs the start service code every 15 seconds

**************************************************************************
do
   MyCode
   wscript.sleep 15000
loop

Sub MyCode
Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_Service WHERE Name = 'W3SVC'"
For Each svc In wmi.ExecQuery(qry)
  If svc.State <> "Running" Then svc.StartService
Next
End Sub
****************************************************************************


2. The below-mentioned script is to kill all the vb scripts running in the background.
****************************************************************************
Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True
WshShell.Run "taskkill /f /im wscript.exe", , True
****************************************************************************

3. The below-mentioned script is to start multiple window services
****************************************************************************
do
   MyCode
   wscript.sleep 15000
loop

Sub MyCode
sComputer = "."
aTargetSvcs= Array ("W3SVC","aspnet_state","AdobeARMservice") 'array of window service
Set oWMIService =  GetObject("winmgmts://./root/cimv2")
Set cServices = oWMIService.ExecQuery("SELECT * FROM Win32_Service")
For Each oService In cServices
 For Each sTargetSvc In aTargetSvcs
  If LCase(oService.Name) = LCase(sTargetSvc) Then
  'MsgBox(oService.State) (commented code to check the status of the service in alert)
    If oService.State <>  "Running" Then 'check the status of the service
      oService.StartService() 
     End If
End if
Next
Next
End Sub
****************************************************************************

4.  vbscript terminate application / vbscript kill process
****************************************************************************



****************************************************************************

5. How to create a vb script
****************************************************************************
1. Open the notepad
2. Copy and paste the above script into the notepad
3. Save it as "test.vbs"
4. To test the same double-click on the "test.vbs"
****************************************************************************

References
1. How to stop a vb script running in windows
2. How do I stop / start service in VBScript?
3. re-run vbs script with time interval.
4. How to get a VBS script to start a service if it is stopped, with no window?
5. VBScript to start multiple services
6. VBA - Message Box