Search code examples
windowsbatch-filecmdwmic

How to filter out wmic process when searching for a process with a specific command line using wmic?


I tried to find an application by the name myapp directly from command prompt and from a batch script by running the following command:

D:\Files>wmic process where "commandline like '%myapp%'" get processid, commandline

CommandLine                                                                  ProcessId  
wmic  process where "commandline like '%myapp%'" get processid, commandline  10744     
myapp myarg1 myarg2 myarg3                                                   2423 

I want to filter out the wmic process entry itself. I tried the following command:

D:\Files>wmic process where "commandline like '%myapp%' and commandline not like '%wmic%'" get processid, commandline

Node - XXXXXXXXXXX
ERROR:
Description = Invalid query

But it outputs an error as shown above.

I tried manually skipping the first line with more +1 but it may happen that the order of output lines (processes) varies.

What could be done to remove the wmic process entry?


Solution

  • Specify any one character within a range by surrounding it with square brackets [].

    Using the java example in your comments:

    In a batch-file (double %% for the like statement)

    @echo off
    wmic process where "commandline like '%%[m]y-complex-application.jar%%'" get processid, commandline
    

    in cmd (single % for like statement)

    wmic process where "commandline like '%[m]y-complex-application.jar%'" get processid, commandline
    

    Why this works

    The [] specifies a range of characters that should or could be matched. For instance when doing ... like '%[abc]md% it will match anything related to amd, bmd and cmd. The trick here is that the character within the [] is matched as a literal character and not with the []. So in the event where we search [m]yapp it literally converts the string to find exactly the word myapp, however, your wmics like statement does not contain this word at all, it contains the word [m]yapp and will not match it.

    Then, some useless information. This trick also works for Linux' grep command as well as windows' findstr

    example (findstr):

    echo myapp | findstr /R "[m]yapp"
    

    result:

    enter image description here

    example (Linux' grep):

    ps -ef | grep "[t]nslsnr"
    

    Result with and without []

    enter image description here