10

FOR当包含在脚本中的命令中时,应该如何编写此 WMIC 命令?

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

下面的代码不起作用:

For /F %%a in (
    'wmic service where ^("name='themes'" and "state='running'"^) get'
) do (
    echo %%a
)
4

3 回答 3

11

还有另一种选择:)

@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

复杂的 WHERE 子句必须用引号或括号括起来。额外的内部'不会导致 FOR /F 出现问题。

我添加了一个额外的 FOR /F 以去除作为 FOR /F 将 WMIC unicode 输出转换为 ANSII 的工件附加到每行末尾的不需要的回车。如果没有额外的 FOR /F,就会有一个额外的行,该行仅由一个回车符组成,该回车符ECHO is off.在末尾产生。

我认为我更喜欢 jeb 的版本,因为它消除了在整个命令中转义的需要,尽管我可能会在 WHERE 子句中使用单引号。例如:

@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

使用我的第一个代码示例中的语法需要转义 GET 子句中的逗号:

@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
于 2013-10-21T14:07:19.960 回答
10
@echo off
For /F "usebackq delims=" %%a in (`wmic service where 'name^="themes" and state^="running"' get`) do (
    echo %%a
)

这对我有用。我使用选项来解决和替代 wmic 语法usebackq没有问题-而不是括号。''

于 2013-10-21T13:15:24.520 回答
10

您可以将完整的 wmic 命令括在单引号中,然后您不需要转义任何内容

FOR /F "delims=" %%a in ('"wmic service where (name="themes" and state="running") get"') do (
  echo %%a
)
于 2013-10-21T13:17:55.440 回答