我希望有一份批处理程序,它可以检查进程notepad.exe
是否存在。
如果notepad.exe
存在,则结束该进程,
否则,批处理程序将关闭自身。
以下是我已经完成的内容:
@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
但是它不起作用。我的代码有什么问题?
我希望有一份批处理程序,它可以检查进程notepad.exe
是否存在。
如果notepad.exe
存在,则结束该进程,
否则,批处理程序将关闭自身。
以下是我已经完成的内容:
@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
将为not found
设置错误级别为0
,对于found
则为1
,这应该能够完成工作。
尽管如此,
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
tasklist
中使用整个值,在find
中只使用前25个字符:tasklist /fi "imagename eq %imgname%" | find /i "%imgname:~0,25%" > nul
。 - Andriy Mtasklist /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
taskkill
呢? - Andriy Mtaskkill
没有改变错误级别... - user2033427