【问题标题】:In a batch file how do I suppress output for a command that is inside FOR /F command在批处理文件中,如何抑制 FOR /F 命令中的命令的输出
【发布时间】:2021-03-27 03:40:44
【问题描述】:

这是一个批处理文件片段的示例:

@echo off

for /f "tokens=1" %%a in ('wmic process where "Caption = 'notepad++.exe'" get Processid ^| findstr /r "[0-9]"') do (
set procid=%%a
)

echo Notepad++ process ID is %procid%

pause

在其中我使用WMIC 获取Notepad++ 的进程ID,使用findstr 提取实际数字,然后使用FOR /F 命令将结果设置为变量以供进一步使用。也许不是最优雅的方式,但它对我有用。

当 Notepad++ 正在运行并且 WIMC 找到它的进程时,它工作得非常好,我得到这样的结果:

Notepad++ process ID is 222648
Press any key to continue . . .

但是,如果 Notepad++ 没有运行,结果如下所示:

No Instance(s) Available.
Notepad++ process ID is
Press any key to continue . . .

这个No Instance(s) Available. 部分是来自 WMIC 的消息,这让我很烦恼。我不希望它打印在屏幕上。

在命令提示符中单独使用命令时,我可以通过在 WMIC 部分的末尾添加 2>&1 来抑制此消息,如下所示:

wmic process where "Caption = 'notepad++.exe'" get Processid 2>&1 | findstr /r "[0-9]"

但是,当我尝试在这样的批处理文件中做类似的事情时:

@echo off

for /f "tokens=1" %%a in ('wmic process where "Caption = 'notepad++.exe'" get Processid 2>&1 ^| findstr /r "[0-9]"') do (
set procid=%%a
)

echo Notepad++ process ID is %procid%

pause

批处理文件崩溃了。

我在这里做错了什么?在这种情况下,抑制 WMIC 输出的正确方法是什么?

谢谢。

【问题讨论】:

  • 你知道的足以逃避^|。您还需要转义>&
  • 非常感谢@Squashman,它成功了!
  • 为了改进方法,将2>&1更改为2^>NUL。不将错误消息传递给findstr 比让它在之后过滤掉它更实际。

标签: batch-file stdout


【解决方案1】:

感谢@Squashman 和@Compo 的建议,我能够修复崩溃并稍微整理一下整个事情。现在的最终变体如下:

@echo off

for /f "tokens=2 delims==" %%a in ('wmic process where "Caption = 'notepad++.exe'" get Processid /value 2^>NUL') do (
set procid=%%a
)

echo Notepad++ process ID is %procid%

pause

2>&1 已更改为2^>NUL>^ 转义),也感谢WMIC/value 开关,它的输出现在可以直接由FOR /F 解析而无需为findstr

【讨论】:

  • 请在您的问题下查看我的评论。
  • 如果您将/value 选项与WMIC 命令一起使用,则不需要FINDSTR 命令。
  • 再次感谢@Squashman,这是个好建议
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
相关资源
最近更新 更多