Search code examples
servicewmi

How can I query WMI to know the name of the user that started a service?


I used several WMI queries in wbemtest to attempt finding out which user started a particular service. The ones that got me "this far" are presented here. I know that if I query the win32_service object like:

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

I obtain only one result (the service I'm looking for), then I double click it to browse the service properties, and found out there's a property called "StartName" which shows the name of the user that started it (that's what I want).

Now, the problem begins when I do:

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

I get Win32_Service = <no key>:

wbemtest

Even without the where clause it shows the same.

What am I missing to make it work?


Solution

  • It's a display thing. Your query works, and if you double-click the result, you'll see the service's StartName:

    wbemtest

    I guess it happens because you don't SELECT the key property - Name. If you add Name to your query, you'll see Win32_Service.Name=name in the results.

    wbemtest

    By the way, in code you'll get both the SELECTed properties and key properties whether or not you query the key properties:

    ' 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