Use WMI to find dependencies of a service and then differentiate dependent Services from dependent Drivers

谁都会走 提交于 2019-12-11 00:49:48

问题


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).


回答1:


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;
  }
}



回答2:


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.



来源:https://stackoverflow.com/questions/6134484/use-wmi-to-find-dependencies-of-a-service-and-then-differentiate-dependent-servi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!