11

How should this WMIC command be written when included in a FOR command in a script?

wmic service where (name="themes" and state="running") get

The code below does not work:

For /F %%a in (
    'wmic service where ^("name='themes'" and "state='running'"^) get'
) do (
    echo %%a
)
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417

3 Answers3

12

Yet another option :)

@echo off
for /f "delims=" %%A in (
  'wmic service where "name='themes' and state='running'" get'
) do for /f "delims=" %%B in ("%%A") do echo %%B

Complex WHERE clauses must be either quoted, or parenthesized. Extra internal ' do not cause problems with FOR /F.

I added an extra FOR /F to strip out the unwanted carriage return that is appended to the end of each line as an artifact of FOR /F converting the WMIC unicode output to ANSII. Without the extra FOR /F, there is an extra line consisting solely of a carriage return that results in ECHO is off. at the end.

I think I prefer jeb's version because it eliminates need for escape throughout the entire command, although I would probably use single quotes within the WHERE clause. For example:

@echo off
for /f "delims=" %%A in (
  '"wmic service where (name='themes' and state='running') get name, pathName"'
) do for /f "delims=" %%B in ("%%A") do echo %%B

Using the syntax in my first code example requires escaping the commas in the GET clause:

@echo off
for /f "delims=" %%A in (
  'wmic service where "name='themes' and state='running'" get name^, pathName'
) do for /f "delims=" %%B in ("%%A") do echo %%B
dbenham
  • 127,446
  • 28
  • 251
  • 390
11
@echo off
For /F "usebackq delims=" %%a in (`wmic service where 'name^="themes" and state^="running"' get`) do (
    echo %%a
)

this one works for me.I've used usebackq option to have no problems with ' and alternative wmic syntax - ' instead of brackets.

npocmaka
  • 55,367
  • 18
  • 148
  • 187
11

You can enclose the complete wmic command in single+double quotes, then you don't need to escape anything

FOR /F "delims=" %%a in ('"wmic service where (name="themes" and state="running") get"') do (
  echo %%a
)
jeb
  • 78,592
  • 17
  • 171
  • 225