Search code examples
wmi

How do I escape comma in WMIC inside like string


I wish to be able to run a query like the following:

wmic path Win32_Service where "DisplayName like 'FooBarService % (X, Y)'" get *

But, it doesn't work because of the comma inside the like string. The error I get is "Invalid Verb." I tried escaping it with a backslash, and I tried escaping it using brackets as underscores are meant to be escaped, and both resulted in the "Invalid Verb." error.

As a less-than-ideal workaround, I can replace the commas with underscores, and it works, but the underscore will match any single character rather than just the comma, so I'd rather find a way to escape the commas.

Is there a way to escape the comma like in this example?


Solution

  • One way I have found to include a comma in the like clause is to place the entire where expression in parentheses. Unfortunately, I also found that this means I cannot include a close paren in the string at the same time (but an open paren is okay). I experimented with the /trace:on option to see what was going on under the covers a little bit and it helped me find a couple things the program accepts:

    Here is an example I got to work with a comma, but it apparently cannot contain a close paren:

    C:\> wmic /trace:on path Win32_Service where (Description like '%(%, %') get DisplayName

    And here is an example I got to work with both open and close parentheses, but apparently it cannot contain a comma (obviously, this is quite similar to your original example):

    C:\> wmic /trace:on path Win32_Service where "Description like '%(TAPI)%'" get DisplayName

    It seems like the parser just isn't complex enough to handle these cases, but with tracing on, you can see the WMI Win32 functions that it uses, so maybe you could write your own program that uses the functions directly. I think IWbemServices::ExecQuery is capable of what you're looking to do.