简体   繁体   中英

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
)
@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.

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

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM