如何在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%
)
我需要通过管道查找,否则即使程序未运行,任务列表也将始终正确完成。
我已经尝试了我能想到的所有变体来逃避|
并在循环中>
,到目前为止没有任何效果。
仅当命令位于第 1 行的括号内时,/f
分隔符选项才有效。我希望命令在循环中。
你只能逃避管道标志,但不要问我为什么。
for /f %%i in ('dir /b /s *_log.xml ^| find "abc" /i /v') do type "%%~i" >> main_log.xml
逃跑 |'s 不会转义>的。这是因为您要用非转义管道结束命令。而您只是告诉操作系统用> <>>和<<更改程序的 STDIN 和 STDOUT 的含义。在命令行中也使用 % 而不是 %%
延迟扩展是在循环中使用变量的常用方法,带有 !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!
)