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

Batch script ignores %ERRORLEVEL% or using previously set one

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

    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 因为如果找不到进程 returns: "process ... was not found on computername"

如果找到进程,returns 就是信息。并且字符串 "found" 不存在。

我几乎什么都试过了。

感谢您的帮助!

你需要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 (and 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
         )
)