Use WMI to find dependencies of a service and then

2019-07-21 15:54发布

There is a code example on MSDN which uses WMI to enumerate all of the dependencies for a particular service: http://msdn.microsoft.com/en-us/library/aa393673(v=vs.85).aspx

This is great...but i've discovered that the dependencies it discovers might not all be of the same type. I was expecting all dependencies to be of type Win32_Service...but sometimes you will find that a dependency that is actually a driver (Win32_SystemDriver).

So..my question is simple - how do I adjust the MSDN code example to perform a check on each dependency and see if it's a Win32_Service or a Win32_SystemDriver so that I can handle it appropriately? Extra points if you provide the solution in jscript (the example on MSDN is vbscript, but i'm using jscript).

2条回答
够拽才男人
2楼-- · 2019-07-21 16:47

Try using this query:

Associators of {Win32_Service.Name="dhcp"} Where AssocClass=Win32_DependentService ResultClass=Win32_SystemDriver

to get only Win32_SystemDriver instances, or

Associators of {Win32_Service.Name="dhcp"} Where AssocClass=Win32_DependentService ResultClass=Win32_Service

to get only Win32_Service instances.

查看更多
地球回转人心会变
3楼-- · 2019-07-21 16:50

The Win32_DependentService association class represents dependent services using the Win32_BaseService base class. So, if you do not define a specific ResultClass in your ASSOCIATORS OR query (as in Uroc's answer), you'll get any Win32_BaseService subclasses - Win32_Service, Win32_SystemDriver as well as Win32_TerminalService.

To handle different object classes differently, you can check for the object's class name using the Path_.Class property. Here's sample JScript code that illustrates this approach:

var strComputer = ".";
var strServiceName = "RpcSs";

var oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!//" + strComputer + "/root/cimv2");

var colItems = oWMI.ExecQuery("ASSOCIATORS OF {Win32_Service.Name='" + strServiceName + "'} WHERE AssocClass=Win32_DependentService Role=Antecedent");
var enumItems = new Enumerator(colItems);

var oItem;
for ( ; !enumItems.atEnd(); enumItems.moveNext()) {
  oItem = enumItems.item();

  switch (oItem.Path_.Class) {
    case "Win32_Service":
      ...
      break;
    case "Win32_TerminalService":
      ...
      break;
    case "Win32_SystemDriver":
      ...
      break;
    default:
      // another class
      ...
      break;
  }
}
查看更多
登录 后发表回答