0

I have to check the service in windows machines and if the service does not exists or is in stopped state then the machine should prompt a message and automatically restart after a certain period of time.

I have tried the below one but its not working.. Can someone help to get this done.

Option Explicit

Const TITLE = "Service Check"
Const SERVICE = "DHCP"
Dim wmi
Dim svcs,svc

Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set svcs = wmi.ExecQuery("Select * from Win32_Service where Name = 'DHCP'")

If svcs.Count = 0 Then
  Call MsgBox(SERVICE & " service does not exist",vbCritical,Title)
  Call reboot(wmi)
Else
  For Each svc In svcs
    If svc.State <> "Running" Then
      Call MsgBox(SERVICE & " service is not running",vbCritical,Title)
      Call reboot(wmi)
    End If
next

End If

Sub reboot(ByRef wmi)
  Dim WSHShell
  Set WSHShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 300"
  Next
End Sub
Katherine Villyard
  • 18,550
  • 4
  • 37
  • 59
  • 1
    Instead of randomly rebooting your server, why not fix the underlying problems that are causing the service to fail? I would be having strong words with anyone who implemented this "solution" on one of my production servers. – Grant May 24 '14 at 01:43
  • 1
    Also, windows handles automatically restarting services on its own. You can configure how it retrys in the service properties, including the option to reboot the server if it can't restart the service. – Grant May 24 '14 at 01:45
  • This is for the desktops and not for servers.Am trying to check the status of an antivirus service which should be always running. If the service is not present then the machine shuts down and the user gets it corrected. Mostly antivirus is not installed in few machines where this will be helpful to me as i would push this script from AD (Group Policy). – Lokanadhan Karthik May 24 '14 at 02:25

1 Answers1

1

I'm not sure I understand why you want to reboot. Also, this is just batch. But:

sc query DHCP | findstr /c:"RUNNING"
if errorlevel 1 shutdown.exe -r -t 300

Although, you might want to consider restarting the service instead:

sc query DHCP | findstr /c:"RUNNING"
if errorlevel 1 net start DHCP
Katherine Villyard
  • 18,550
  • 4
  • 37
  • 59