2010-10-08 54 views
3

我想使用VBScript來檢查後臺打印程序服務是否啓動,如果不啓動它,下面的代碼檢查服務狀態,但我需要一些幫助修改此,以便我可以檢查它是否啓動。使用VBScript如何檢查後臺打印程序服務是否已啓動,如果不啓動它?

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 

非常感謝 史蒂芬

回答

5

如何這樣的事情。如果該命令尚未運行,該命令將啓動它。無需事先檢查。

Dim shell 
Set shell = CreateObject("WScript.Shell") 
shell.Run "NET START spooler", 1, false 
+0

肯定不需要掏出來調用外部命令。看到我的答案。 – ghostdog74 2010-10-08 02:33:15

+1

當然沒有理由不要。爲什麼重新發明輪子? – JohnFx 2010-10-08 02:35:21

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 

注意,你也可以使用objService.started來檢查其啓動。

0

只是爲了completeless,這裏是一個使用Shell.Application對象的替代變種:

Const strServiceName = "Spooler" 

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

或者乾脆:

Set oShell = CreateObject("Shell.Application") 
oShell.ServiceStart "Spooler", False ''# This returns False if the service is already running 
相關問題