批处理脚本忽略%ERRORLEVEL%或使用先前设置的%ERRORLEVEL%

时间:2015-06-10 06:13:43

标签: batch-file process errorlevel

我编写了一个批处理脚本来查明特定进程是否在计算机上运行:

    for /f %%a in (computers.txt) do (
        PsList.exe \\%%a -e "process" > result.txt
        Find /i "found" < result.txt
        IF "%ERRORLEVEL%" == "0" echo %%a >> Computers_without_process.csv
)

我做了Find /i "found" < result.txt,因为如果找不到进程,则返回:“在计算机名称上找不到进程...”

如果找到该过程,则返回其信息。字符串“找到”不存在。

我几乎尝试过任何事情。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您需要delayed expansion

setlocal enableDelayedExpansion    
for /f %%a in (computers.txt) do (
        PsList.exe \\%%a -e "process" > result.txt
        Find /i "found" < result.txt
        IF "!ERRORLEVEL!" == "0" echo %%a >> Computers_without_process.csv
)

或者您可以使用conditional execution(和pipes):

setlocal enableDelayedExpansion    
for /f %%a in (computers.txt) do (
        PsList.exe \\%%a -e "process" | Find /i "found" >nul 2>nul && (
           echo %%a >> Computers_without_process.csv
         )
)