Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine For /F with WMIC + WHERE clause + AND clause

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
)
like image 893
ElektroStudios Avatar asked Oct 21 '13 13:10

ElektroStudios


1 Answers

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
like image 87
dbenham Avatar answered Nov 09 '22 11:11

dbenham