views:

16

answers:

3

Hi all,

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

+1  A: 

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
certainly no need to shell out to call external commands. see my answer.
ghostdog74
certainly no reason not to either. Why reinvent the wheel?
JohnFx
+2  A: 
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
A: 

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