Querying process by CommandLine

3.2k Views Asked by At

I'm trying to do the following query in WMI:

SELECT ProcessID from Win32_Process where CommandLine='C:\Windows\system32\calc.exe'

But I got an "Invalid query" error. I also tried with:

SELECT ProcessID from Win32_Process where CommandLine='C:\\Windows\\system32\\calc.exe'

And still get the same error, also I tried to change the single quotes to double quotes but it didn't work.

Does anybody know if its possible to do that query?

2

There are 2 best solutions below

0
On

Yes and No. Depends on how calc.exe is spawned. For instance, when I type calc into cmd.exe window, my calc gets a commandline of 'calc'. When I type calc into powershell.exe console, it get's a full path. The Win32_Process 'commandline' variable is not reliable IMO. Here are some differing result to prove my point.

cmd.exe                              4028 C:\Windows\system32\cmd.exe  /K set
calc.exe                             2580 "C:\Windows\system32\calc.exe"
notepad.exe                          3612 "C:\Windows\system32\notepad.exe"
cmd.exe                              2864 "C:\Windows\system32\cmd.exe"
conhost.exe                           480 \??\C:\Windows\system32\conhost.exe
WMIC.exe                             3596 wmic
WmiPrvSE.exe                         2272 C:\Windows\system32\wbem\wmiprvse.exe
cmd.exe                              2296 "C:\Windows\system32\cmd.exe"
conhost.exe                          3708 \??\C:\Windows\system32\conhost.exe
notepad.exe                          1284 "C:\Windows\system32\notepad.exe"
calc.exe                             1736 calc
powershell.exe                       3136 "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe"

So to make it work you will need an OR clause in your SQL statement, matching 'calc' or "C:\Windows\system32\calc.exe"

0
On

In addition Windows adds sometimes an additional whitespace into the command line after the ExecutablePath and before the first parameter.

Even if there is no paramter and the Executable was lanched with quotes (because of whitespaces in the path) then in most cases the command line is the ExecutablePath and a final whitespace at the end.

That cost me some hours to find this. Cheers!