Check and Restart a Service

Uses WMI to determine if a service (in this case ‘Microsoft Exchange Information Store’) is running, and restarts the service if required.
Usage: cscript SRV_RestartService.vbs
Add a text file called “servers.txt” and containing all machine names (line by line) into the same directory. The Script will query each machine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Dim objFileSystem, objInputFile
Dim strInputFile, inputData, strData
 
Const OPEN_FILE_FOR_READING = 1
Do
strDate = year(date()) & "-" & right("0" & month(date()),2) & "-" & right("0" & day(date()),2)
strInputFile = "./servers.txt"
strOutputFile = "./MSX_" & strDate & ".txt"
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set objInputFile = objFileSystem.OpenTextFile(strInputFile, OPEN_FILE_FOR_READING)
Set objOutputFile = objFileSystem.CreateTextFile(strOutputFile, TRUE)
 
inputData = Split(objInputFile.ReadAll, vbNewline)
For each strData In inputData
strComputer = strData
'WScript.Echo strComputer

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Service WHERE DisplayName = 'Microsoft Exchange Information Store'",,48)
 
        For Each objItem in colItems
 
        If objItem.State<>"Running" Then 
                'WScript.Echo Time & "  The " & objItem.DisplayName & " on " & objItem.SystemName & " was returning: [" & objItem.State & "]"
                objOutputFile.WriteLine (Time & "  The " & objItem.DisplayName & " on " & objItem.SystemName & " was returning: [" & objItem.State & "]")
                objItem.StartService()
                Set WshShell = WScript.CreateObject("WScript.Shell")
                WshShell.Run ("NET SEND LOCALHOST " & "  The " & objItem.DisplayName & " Service on " & objItem.SystemName & " was returning: [" & objItem.State & "]! Automatic restart in Progress...")
                WScript.Sleep(120000)
        End If
 
        Next
Next
 
objInputFile.Close
objOutputFile.Close
Set objFileSystem = Nothing
WScript.Sleep(30000)
 
Loop

Leave a Reply