如何查询WMI以了解启动服务的用户的名称?

时间:2014-01-09 22:18:37

标签: service wmi

我在wbemtest中使用了几个WMI查询来尝试找出哪个用户启动了特定服务。那些让我“走得这么远”的人在这里展示。 我知道如果我查询win32_service对象,如:

select * from win32_service where name like '%SERVICENAME%'

我只获得一个结果(我正在寻找的服务),然后我双击它以浏览服务属性,并发现有一个名为“ StartName ”的属性,它显示了名称启动它的用户(这就是我想要的)。

现在,当我这样做时,问题就出现了:

 select StartName from win32_service where name like '%SERVICENAME%'

我得到Win32_Service = <no key>

wbemtest http://imageshack.com/a/img4/3029/19qs.jpg

即使没有where子句,它也会显示相同的内容。

我错过了什么让它起作用?

2 个答案:

答案 0 :(得分:2)

这是展示品。您的查询有效,如果您双击结果,您会看到该服务的StartName

wbemtest

我想这是因为你没有SELECT关键属性 - Name。如果您在查询中添加Name,则会在结果中看到Win32_Service.Name= name

wbemtest

顺便说一句,在代码中,无论是否查询关键属性,您都将获得SELECT ed属性和关键属性:

' VBScript example
strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery( _
    "SELECT StartName FROM Win32_Service WHERE Name LIKE '%winmgmt%'",,48) 
For Each objItem in colItems 
    Wscript.Echo "Name: " & objItem.Name ' <-- Name is there, even though we didn't query it
    Wscript.Echo "StartName: " & objItem.StartName
Next

答案 1 :(得分:2)

我为C#编写了一个实际工作的代码。

    public Service GetServiceDetails(string serviceName)
    {
      using (var managementBaseObject = new ManagementObjectSearcher(new SelectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName))).Get())
      {
        ManagementObject mo = managementBaseObject.Cast<ManagementObject>().FirstOrDefault();

        if (mo == null) return null;

        var service = new Service
        {
          AcceptPause = mo["AcceptPause"] != null && (bool) mo["AcceptPause"],
          AcceptStop = mo["AcceptStop"] != null && (bool)mo["AcceptStop"],
          Caption =  mo["Caption"] != null ? mo["Caption"].ToString() : string.Empty,
          Description =  mo["Description"] != null ? mo["Description"].ToString() : string.Empty,
          DisplayName = mo["DisplayName"] != null ? mo["DisplayName"].ToString() : string.Empty,
          Name = mo["Name"] != null ? mo["Name"].ToString() : string.Empty,
          PathName = mo["PathName"] != null ? mo["PathName"].ToString() : string.Empty,
          ProcessId = mo["ProcessId"] != null ? Convert.ToInt32(mo["ProcessId"]) : 0,
          ServiceType = mo["ServiceType"] != null ? mo["ServiceType"].ToString() : string.Empty,
          Started = mo["Started"] != null && (bool)mo["Started"],
          StartMode = mo["StartMode"] != null ? mo["StartMode"].ToString() : string.Empty,
          StartName = mo["StartName"] != null ? mo["StartName"].ToString() : string.Empty,
          State = mo["State"] != null ? mo["State"].ToString() : string.Empty,
          Status = mo["Status"] != null ? mo["Status"].ToString() : string.Empty,
        };
        return service;
      }
    }