【问题标题】:Include pipe and redirect inside a for loop在 for 循环中包含管道和重定向
【发布时间】:2013-10-22 18:20:29
【问题描述】:

如何在 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%
)

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

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

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

【问题讨论】:

  • 如果您说出您看到的错误或错误行为与您期望看到的相比,将会很有帮助。您不需要在 for 循环内转义管道或重定向。打开 echo 以查看您的批处理文件正在运行哪些命令。这工作正常:for %%m in (chrome.exe abc.exe notepad++.exe) do tasklist /fi "IMAGENAME eq %%m" /nh | find /i "%%m" >>results.txt
  • 另外,您需要在循环中使用 err_count 周围的延迟扩展。放入setlocal EnableDelayedExpansion,然后在循环中使用!err_count!。在命令行输入help set 或谷歌搜索更多信息。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    for /f %%i in ('dir /b /s *_log.xml ^| find "abc" /i /v') do type "%%~i" >> main_log.xml
    

    转义 | 不转义 >。这是因为您正在使用非转义管道结束命令。而您只是告诉操作系统用 > > 和

    【讨论】:

      【解决方案3】:

      延迟扩展是在循环中使用变量的常用方法,带有 !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!
      )
      

      【讨论】:

        猜你喜欢
        • 2019-11-11
        • 2020-08-24
        • 2011-07-11
        • 1970-01-01
        • 1970-01-01
        • 2014-11-21
        • 1970-01-01
        • 2014-01-13
        • 1970-01-01
        相关资源
        最近更新 更多