开发者

How to Catch WMI Errors

开发者 https://www.devze.com 2023-02-19 03:39 出处:网络
I want to use wmi to stop a service if it is running. Below is the code in vbscript. The problem is, GetObject, startService, and ExecuteQuery commands may get errors because of various reasons. For

I want to use wmi to stop a service if it is running. Below is the code in vbscript.

The problem is, GetObject, startService, and ExecuteQuery commands may get errors because of various reasons. For example, after issuing "stopService" command, the state of the service may become "stopping", instead of "stopped", and th开发者_StackOverflow中文版e script is hanging there for quite some time. Sometimes, error messages such as "RPC is not available" was returned. Seems there is no catch exception machanism built into vbscript. Most of the examples I saw online never considered such situation. Does anybody know there is a good way to catch such kind of errors, and force these command (note: not service itself) to abort?

 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

[/code]


You must read this article from Microsoft To Err Is VBScript in this link you will find everything which you must know about handle errors using the the WMI and VbScript.

0

精彩评论

暂无评论...
验证码 换一张
取 消