0

如何在 cmd for 循环中使用管道或重定向?

我的示例脚本是(目的是查看是否有一系列特定的程序/服务正在运行:

for  %%m in ( **{list of individual program names}** ) do (
tasklist /FI "IMAGENAME eq %%m" /NH   ^| find /i "%%m"  
if "%errorlevel%" EQU "1" set /a err_count=%err_count%+1
echo checking tasklist item %%m , count is %err_count%
)

我需要通过管道查找,否则即使程序没有运行,任务列表也将始终完成而不会出错。

我已经尝试了我能想到的所有变体来逃避|>循环,但到目前为止没有任何效果。

仅当命令位于第 1 行的括号内时,/f分隔符选项才有效。我希望命令位于循环内。

4

3 回答 3

1

你只能避开管道标志,但不要问我为什么。

于 2013-12-03T01:44:43.497 回答
0
for /f %%i in ('dir /b /s *_log.xml ^| find "abc" /i /v') do type "%%~i" >> main_log.xml

转义 | 不转义 >。这是因为您正在使用非转义管道结束命令。而您只是告诉操作系统用 > < >> 和 << 更改程序的 STDIN 和 STDOUT 的含义。在命令行也使用 % 而不是 %%

于 2013-10-22T19:07:48.533 回答
0

延迟扩展是在循环中使用变量的常用方法,使用 !variable! 句法。

管道是循环中的普通字符,不需要转义。

@echo off
setlocal enabledelayedexpansion
for  %%m in ( **{list of individual program names}** ) do (
tasklist /FI "IMAGENAME eq %%m" /NH    | find /i "%%m"  
if errorlevel 1 set /a err_count+=1
echo checking tasklist item %%m , count is !err_count!
)
于 2013-10-22T20:22:34.027 回答