【发布时间】:2011-03-24 09:21:34
【问题描述】:
如果服务正在运行,我想使用 wmi 来停止它。下面是vbscript中的代码。
问题是,GetObject、startService 和 ExecuteQuery 命令可能会因为各种原因而出错。例如,发出“stopService”命令后,服务的状态可能变为“正在停止”,而不是“已停止”,并且脚本在那里挂了相当长的时间。有时会返回诸如“RPC 不可用”之类的错误消息。似乎 vbscript 中没有内置捕获异常机制。我在网上看到的大多数例子都没有考虑过这种情况。有谁知道有一种很好的方法可以捕获此类错误并强制这些命令(注意:不是服务本身)中止?
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery ("Select * from Win32_Service where Name = '" & strService & "'")
For Each objService in colServiceList
If objService.State = "Running" Then
strObjService.StopService
Wscript.Sleep 2000
myColServiceList = myObjWMIService.ExecQuery _
("Select * from Win32_Service where Name = '" & strService & "'")
For each myObjService In myColServiceList
objState = myObjService.State
End If
End If
[/代码]
【问题讨论】:
标签: exception-handling vbscript wmi