Search code examples
vbscriptpathadminpid

Retrieve PID of process by path, not name, with multiple users


I'm trying to retrieve the PID of all the instances of a software in a specific location. It's a portable app, so there may be multiple copies of it across the system, but I'm interested in one specific location only. Also, it can be startes by different users simultaneously, admins as well standard users.

I copied this VBS code (from http://msdn.microsoft.com/en-us/library/windows/desktop/aa394372%28v=vs.85%29.aspx)

strComputer = "."

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'foobar.exe'")

For Each objProcess in colProcesses
    If objProcess.GetOwner(User, Domain) = 0 Then
        WScript.Echo "Process " & objProcess.Name & " belongs to " & Domain & "\" & User
    Else
        WScript.Echo "Problem " & Rtn & " getting the owner for process " & objProcess.Caption
    End If
Next

I now need to distinguish the full path of the app. If I use objProcess.ExecutablePath (5th line) I can see the full path of the instances launched by the current user only, while using Where ExecutablePath (3rd line) gives some sort of syntax error.

Any help?


Solution

  • As documented you'll need admin privileges (more specifically SeDebugPrivilege) to see processes of other users.

    The syntax error you get when using a Where ExecutablePath = '...' clause is probably because you didn't escape backslashes in the path. Backslashes in WMI queries escape characters with special meaning, so you need to double them to get literal backslashes:

    Select * From Win32_Process Where ExecutablePath = 'C:\\Windows\\notepad.exe'
    

    I'm merely guessing here, though, since you decided to omit both the actual query with the Where clause and the error it raised.