3

I'd like to use VBScript to check if the Spooler service is started and if not start it, the code below checks the service status but I need some help modifying this so I can check if it is started.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colRunningServices 
    Wscript.Echo objService.DisplayName  & VbTab & objService.State
Next

Many thanks Steven

StevenL
  • 147
  • 1
  • 1
  • 8

3 Answers3

5

How about something like this. This command will start it if it isn't already running. No need to check in advance.

Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run "NET START spooler", 1, false
JohnFx
  • 34,542
  • 18
  • 104
  • 162
1
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
    ("select State from Win32_Service where Name = 'Spooler'")

For Each objService in colRunningServices
    If objService.State <> "Running" Then
        errReturn = objService.StartService()
    End If
Next

Note you can also use objService.started to check if its started.

ghostdog74
  • 327,991
  • 56
  • 259
  • 343
0

Just for the completeless, here's an alternative variant using the Shell.Application object:

Const strServiceName = "Spooler"

Set oShell = CreateObject("Shell.Application")
If Not oShell.IsServiceRunning(strServiceName) Then
  oShell.ServiceStart strServiceName, False
End If

Or simply:

Set oShell = CreateObject("Shell.Application")
oShell.ServiceStart "Spooler", False    ''# This returns False if the service is already running
Helen
  • 87,344
  • 17
  • 243
  • 314