在for循环中包含管道和重定向

时间:2013-10-22 18:20:29

标签: loops redirect batch-file for-loop pipe

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

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

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%
)

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

我已经尝试过我可以想到的每个变体来逃避循环中的|>,到目前为止还没有任何效果。

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

3 个答案:

答案 0 :(得分:1)

你必须只逃避管道标志,但不要问我为什么。

答案 1 :(得分:0)

for /f %%i in ('dir /b /s *_log.xml ^| find "abc" /i /v') do type "%%~i" >> main_log.xml

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

答案 2 :(得分:0)

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

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

@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!
)
相关问题