要检查批处理程序中是否存在进程(Batch program to to check if proce

2019-07-21 18:36发布

我想一个批处理程序,如果程序将检查notepad.exe存在。

如果 notepad.exe存在,它将结束进程,

否则批处理程序将关闭本身。

这里是我做了什么:

@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

但是,这是行不通的。 什么是错在我的代码?

Answer 1:

TASKLIST不设置错误级别。

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

应该做的工作,因为“:”应该出现在TASKLIST只有在任务中没有找到输出,因此FIND将设置ERRORLEVEL以0not found1found

尽管如此,

TASKKILL / F / IM “Notepad.exe的”

如果存在的话会杀了一个记事本的任务 - 如果没有记事本任务存在它可以做什么,所以你并不真的需要测试 - 除非有你想要做点别的......也许像

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit

这似乎做,因为你问 - 如果存在的话,那么退出杀记事本程序 - 否则继续批



Answer 2:

这是一个行的解决方案

它将运行的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.


Answer 3:

TASKLIST不设置退出代码,你可以检查在一个批处理文件。 一个解决方法,以检查出的代码可以解析它的标准输出(你目前重定向到NUL )。 显然,如果过程中发现, TASKLIST将显示其详细信息,包括图像名称了。 因此,你可以只使用FINDFINDSTR以检查TASKLIST的输出包含您在请求中指定的名称。 双方FINDFINDSTR设置一个非空退出代码,如果搜索没有成功。 所以,这会工作:

@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可言。 不像TASKLISTTASKKILL不设置退出代码。 特别是,如果因为它根本不存在也不可能终止一个进程,它会设定的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


Answer 4:

这就是为什么它不工作,因为你的代码的东西是不对的,这就是为什么它总是退出和脚本执行器将它读成不具有可操作性批处理文件,防止其退出和停止,因此必须

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


Answer 5:

试试这个:

@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


文章来源: Batch program to to check if process exists