如何简单地从批处理文件中杀死一个进程?

问题描述

我的代码需要检查notepad.exe下是否列出了tasklist。如果是这样,批处理文件关闭它。

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

解决方法

tasklist始终返回错误级别0,即使找不到任何内容也是如此。为了解决此问题,您应该将tasklist的输出通过管道传递到find,如果找到该进程,则将返回错误级别0,如果找不到该进程,则将返回错误级别1。

@echo off
tasklist | find /I "notepad.exe" >nul
if "%errorlevel%"=="0" taskkill /f /im "notepad.exe"