我有一个批处理文件,需要杀死符合关键字的进程。这是我的批处理文件:
@echo off
REM tkill.bat
IF [%1] == [] GOTO Syntx
tasklist | find /i "%1%" > ttt.txt
set /p line=<ttt.txt
for /f %%G in ("%line%") do set "pp=%%G"
if [%pp] == [] GOTO endit
taskkill /f /im %pp%
del ttt.txt
goto endit
:syntx
echo Syntax:
echo tkill partial_process_name
:endit
set line=
让我们说我想杀死所有歌剧浏览器进程。所以我跑:
tkill opera
我得到这个输出
C:\Windows\system32>tkill opera
SUCCESS: The process "opera.exe" with PID 3572 has been terminated.
SUCCESS: The process "opera.exe" with PID 9320 has been terminated.
SUCCESS: The process "opera.exe" with PID 6628 has been terminated.
SUCCESS: The process "opera.exe" with PID 2220 has been terminated.
SUCCESS: The process "opera.exe" with PID 4184 has been terminated.
SUCCESS: The process "opera.exe" with PID 5816 has been terminated.
SUCCESS: The process "opera.exe" with PID 9816 has been terminated.
SUCCESS: The process "opera.exe" with PID 7416 has been terminated.
SUCCESS: The process "opera.exe" with PID 684 has been terminated.
SUCCESS: The process "opera.exe" with PID 4688 has been terminated.
所以我检查是否有散乱的进程
C:\Windows\system32>tasklist | find /i "opera"
C:\Windows\system32>
没有。 然后,我再次运行相同的命令,并查看结果:
tkill opera
ERROR: The process "opera.exe" not found.
这是我的问题:内存中没有名为Opera.exe的进程。因此,我的
tasklist | find /i "%1%" > ttt.txt
命令应导致文件为空。但是opera.exe的名称一直卡在某个地方,直到我关闭dos提示符并打开一个新的提示符,或者使用实际上正在运行并被杀死的不同进程名运行同一命令。然后新名称卡在内存中,例如:
C:\Windows\system32>tkill notepad.exe
SUCCESS: The process "notepad.exe" with PID 5952 has been terminated.
C:\Windows\system32>tkill notepad.exe
ERROR: The process "notepad.exe" not found.
C:\Windows\system32>tkill neon
ERROR: The process "notepad.exe" not found.
C:\Windows\system32>
我对如何分配Windows变量的理解有些遗漏,但是我不知道有什么遗漏。任何帮助表示赞赏。
答案 0 :(得分:0)
已测试
尝试将setlocal
和endlocal
添加到脚本中。
使用setlocal enabledelayedexpansion
并在必要时使用!
也可以正常工作。
@echo off
setlocal
REM tkill.bat
IF [%1] == [] GOTO Syntx
tasklist | find /i "%1%" > ttt.txt
set /p line=<ttt.txt
for /f %%G in ("%line%") do set "pp=%%G"
if [%pp] == [] GOTO endit
taskkill /f /im %pp%
del ttt.txt
endlocal
goto endit
:syntx
echo Syntax:
echo tkill partial_process_name
:endit
set line=
如果没有创建pp
作为环境变量,则可能会存储找到的最后一个进程。
不需要多余的详细说明:
在原始batch
中,pp
始终存储找到的最后一个进程。但是请注意,如果我们执行三个相同且连续的执行,则仅第二次执行脚本。没有启用延迟扩展,它将在解析时而非执行时采用pp
的值。由于第二次执行set pp=
,因为未找到任何进程。原始脚本第三次运行正常。
答案 1 :(得分:0)
由于让该程序在任何正在运行的进程中的任何位置匹配输入字符串都太麻烦了,我将在您的tkill.bat
文件中提供以下简单得多的语法:
@If "%~1"=="" (Echo Syntax:&Echo tkill partial_process_name)Else TaskKill /Fi "ImageName Eq %~1*" /F /T
如果需要,您可以将以上内容分成多行以便于阅读:
@Echo Off
If "%~1"=="" (
Echo Syntax:
Echo tkill partial_process_name
) Else TaskKill /Fi "ImageName Eq %~1*" /F /T
这不需要写入,读取和删除文件,也不需要定义任何变量。也不依赖find.exe
(尤其是ImageName Eq
选项已经不区分大小写)。您还将注意到,为了使用Tasklist
,无需检查TaskKill
的输出,如果找不到匹配的进程,它将无法“杀死”它并提供{{ 1}}消息,(而不是您当前收到的INFO:
消息。)。