我想要一个批处理程序,它将检查进程notepad.exe
存在。
如果 notepad.exe
存在,它会结束进程,
否则批处理程序将自行closures。
这是我所做的:
@echo off tasklist /fi "imagename eq notepad.exe" > nul if errorlevel 1 taskkill /f /im "notepad.exe" exit
但它不起作用。 我的代码有什么问题?
TASKLIST
不会设置错误级别。
echo off tasklist /fi "imagename eq notepad.exe" |find ":" > nul if errorlevel 1 taskkill /f /im "notepad.exe" exit
应该做的工作,因为“:”应该出现在TASKLIST
输出只有当任务没有找到,因此FIND
将错误级别设置为0
not found
, 1
found
尽管如此,
taskkill / f / im“notepad.exe”
如果存在的话会杀死一个记事本任务 – 如果没有记事本任务存在,它可以不做任何事情,所以你不需要测试 – 除非有别的你想做的事情…也许
echo off tasklist /fi "imagename eq notepad.exe" |find ":" > nul if errorlevel 1 taskkill /f /im "notepad.exe"&exit
这似乎是按照你的要求去做 – 杀死记事本进程(如果存在的话),然后退出 – 否则继续进行批处理
这是一个单线解决方案 。
它只会运行taskkill,如果这个进程真的在运行,否则它只会告知它没有运行。
tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.
这是运行过程中的输出:
notepad.exe 1960 Console 0 112,260 K SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.
这是在没有运行的情况下的输出:
process "notepad.exe" not running.
TASKLIST
不会设置可以在批处理文件中检查的退出代码。 检查退出代码的一个解决方法可能是解析其标准输出(您目前正在将其重定向到NUL
)。 显然,如果找到这个进程, TASKLIST
将会显示它的细节,包括图像的名字。 因此,您可以使用FIND
或FINDSTR
来检查TASKLIST
的输出是否包含您在请求中指定的名称。 如果搜索不成功, FIND
和FINDSTR
设置一个非空的退出代码。 所以,这将工作:
@echo off tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul if not errorlevel 1 (taskkill /f /im "notepad.exe") else ( specific commands to perform if the process was not found ) exit
还有一个不涉及TASKLIST
的选择。 与TASKLIST
不同, TASKKILL
确实设置了退出代码。 特别是,如果因为它不存在而无法终止一个进程,它将设置128的退出代码。您可以检查该代码以执行您在特定进程中可能需要执行的特定操作不存在:
@echo off taskkill /f /im "notepad.exe" > nul if errorlevel 128 ( specific commands to perform if the process was not terminated because it was not found ) exit
QPROCESS "myprocess.exe">NUL IF %ERRORLEVEL% EQU 0 ECHO "Process running"
上面的代码在Windows 7中进行了测试,具有管理员权限的用户。
这就是为什么它不工作,因为你编码的东西是不正确的,这就是为什么它总是退出,脚本执行者将读取它作为不可操作的批处理文件,防止它退出和停止,所以它必须
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL if "%ERRORLEVEL%"=="0" ( msg * Program is running goto Exit ) else if "%ERRORLEVEL%"=="1" ( msg * Program is not running goto Exit )
而不是
@echo off tasklist /fi "imagename eq notepad.exe" > nul if errorlevel 1 taskkill /f /im "notepad.exe" exit
尝试这个:
@echo off set run= tasklist /fi "imagename eq notepad.exe" | find ":" > nul if errorlevel 1 set run=yes if "%run%"=="yes" echo notepad is running if "%run%"=="" echo notepad is not running pause