我如何从批处理中杀死除当前 运行 之外的所有 cmd.exe?

how do I kill all cmd.exe except the one currently running from batch?

这几天我一直在写一个脚本,我认为它很容易,但似乎并不容易,我明白为什么。我的问题是如何解决它。

我需要解释的批处理脚本:

我有一个 运行 在 cmd.exe 中的脚本,它可以做很多事情,比如将大量文件从一个位置移动到另一个位置。让我们称之为 movefile.cmd。这个脚本有效,但有时会停止(很少 - 让我们不要讨论为什么和那个脚本)。重要的是这个脚本总是 运行s,所以我的想法是创建一个退出 cmd.exe 的批处理,然后每隔一小时左右重新打开脚本。让我们调用这个脚本 restartcmd.bat

听起来很简单,因为我可以做到这一点:

@echo off

:loop

start c:\script\movefile.cmd 

Timeout /nobreak /t 3600

Taskkill cmd.exe

goto loop

但显然这不起作用,因为我的新脚本也在 cmd.exe 中 运行,所以它也会终止这个进程。

我试过的:

所以我复制了一份cmd.exe并重命名为dontkillthis.exe。我 运行 dontkillthis.exe 然后从 dontkillthis.exe 打开 restardcmd.bat - 这非常有效!但我需要能够只双击我的脚本而不是那样做。为什么?因为它应该尽可能简单,而且我希望我的 restartcmd.bat 位于我的启动文件夹中。

我一直在考虑获取 cmd.exe 的确切进程 ID 并关闭它以便我的 dontkillthis.exe 将保留的想法,但我似乎无法确定它。尝试了这里写的所有内容 how to kill all batch files except the one currently running ,但我无法让它工作。

我不确定我是否感到困惑,或者这样做是否真的有点困难。

非常感谢您的帮助。

此致

MO

如果能得到 movefile.cmd 的 PID 会好很多。如果您可以编辑它,请添加一个 title MyMoveFileProcess 并使用

获取它的 PID
for /f "tokens=2" %%i in ('tasklist /v ^|find "MyMoveFileProcess"') do set PID=%%i

然后你可以用taskkill /pid %pid%

杀死它

除了更改您的 movefile.cmd,您还可以仅以标题开头:

start "MyMoveFileProcess" c:\script\movefile.cmd 

首先您需要当前 CMD 实例的 PID。该主题有been discussed here . I will offer you my solution - getCmdPID.bat

这是脚本(getCmdPID 应该在同一目录中):

@echo off

call getCmdPID
set "current_pid=%errorlevel%"

for /f "skip=3 tokens=2 delims= " %%a in ('tasklist /fi "imagename eq cmd.exe"') do (
    if "%%a" neq "%current_pid%" (
        TASKKILL /PID %%a /f >nul 2>nul
    )
)

此外,仅供参考。 我发现可以根据标题停止和启动其他 cmd 文件,这将是解决我的问题的替代方法。所以假设 movefile.cmd 在其脚本中有这一行:Title "movefile"(“”很重要)。 然后我可以在 restartcmd.bat 中写 taskkill /F /FI "WindowTitle eq Administrator: \"movefile"" /T :)

通常使用以下命令我应该能够找到PID。不幸的是,情况并非如此。

title exclude &tasklist /NH /v /fo csv /FI "WINDOWTITLE ne exclude*" /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running"

所以为了实现我的目标,我使用了以下命令: FIND /I "exclude" 1>NUL

@echo off
TITLE exclude
(for /f "usebackq  tokens=*" %%a in (`tasklist /NH /v /fo csv /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running"`) do (
  (
    echo %%a | FIND /I "exclude" 1>NUL
  ) || ( 
    for /f "usebackq tokens=2 delims=," %%i in (`echo %%a`) do (
      echo TASKKILL /PID %%~i /f
    )
  )
)
)>_output-taskill.txt
TYPE _output-taskill.txt

另一种在一行中杀死所有进程的方法是在命令 taskkill 上使用过滤器,过滤器应如下所示:

TASKKILL /F /FI "PID ne XXXX" /FI "IMAGENAME eq cmd.exe" /IM cmd.exe

eq (equal)

ne (not equal)

gt (greater than)

lt (lesser than)

@echo off
TITLE exclude
(for /f "usebackq tokens=2 delims=," %%a in (`tasklist /NH /v /fo csv /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running" ^| FIND /I "exclude"`) do (
    echo TASKKILL /F /FI "PID ne %%~a" /FI "IMAGENAME eq cmd.exe" /IM cmd.exe
  )
)>_output-taskill.txt
TYPE _output-taskill.txt

几行代码将帮助您实现这一目标:

TITLE exclude
taskkill /IM cmd.exe /FI "WINDOWTITLE ne exclude*"

我找到了一个解决方案,它利用文本文件来跟踪 bat 文件拥有的所有先前 PID。它试图静静地杀死它们,然后将当前的 PID 添加到列表中。

如果您不希望它杀死旧的、已经存在的进程,只需将具有 "taskkill" 的行替换为您想用它做的任何事情。

(可能需要您 运行 作为管理员才能获得终止重复进程的权限。如果您不这样做,请参阅下面的权限提升代码以了解可选实施不想每次都运行作为管理员。)

@echo off
set WorkingDir=%cd% 
if exist MostRecentPID.txt ( del "PIDinfo.txt"  /f /q ) > nul
cd ..\..\..\..\..\..\..
title mycmd
tasklist /v /fo csv | findstr /i "mycmd" > %WorkingDir%\PIDinfo.txt
set /p PIDinfo=<%WorkingDir%\PIDinfo.txt

REM below, the 11 means get substring starting a position 11 with length of 5 characters. The tasklist command gives a long and verbose value so this will get just the PID part of the string.
set PID5chars=%PIDinfo:~11,5%
set PID4chars=%PIDinfo:~11,4%

if exist PreviousPIDs.txt (
    for /F "tokens=*" %%A in (PreviousPIDs.txt) do taskkill.exe /F /T /PID %%A > nul 2>&1
    goto CheckIfFourCharPID
)

:CheckIfFourCharPID
if %PID4chars% gtr 8100 (
    for /F "tokens=*" %%A in (PreviousPIDs.txt) do taskkill.exe /F /T /PID %%A > nul 2>&1
    echo %PID4chars% >> "PreviousPIDs.txt"
) else (
    echo %PID5chars% >> "PreviousPIDs.txt"
)

解释:(警告:非常技术性)

-此解决方案获取任务列表命令的子字符串以仅获取 PID。 cmd.exe 不会有大于 18100 的 PID,因此请检查 PID4chars 是否大于 8100,以便我们知道它是 4 位数字还是 5 位数字

案例 1:像 17504 这样的 5 位 PID 具有 PID5chars val 17504 和 PID4chars val 1750,因此我们将 PID5chars 添加到 PID 的文本文件中以杀死

案例 2:像 8205 这样的 4 位 PID 的 PID5chars val 为 8205" 和 PID4chars val 为 8205,因此我们将 PID4chars 添加到 PID 的文本文件中以杀死

情况 3:4 位 PID,如 4352,其 PID5chars 值为 4352",PID4chars 值为 4352,因此我们将 PID4chars 添加到 PID 的文本文件中以终止


可选权限海拔代码

(把它放在你的 bat 文件的顶部,它会自动-运行 它作为管理员。)

    @echo off
    setlocal DisableDelayedExpansion

    set "batchPath=%~0"
    for %%k in (%0) do set batchName=%%~nk
    cd ..\..\..\..\..\..\..\..
    if exist %cd%\Temp (
    set temp=%cd%\Temp
    goto vbsGetPrivileges
    )
    if exist %cd%\Windows\Temp (
    set temp=%cd%\Windows\Temp
    goto vbsGetPrivileges
    )
    set temp=%cd%

    :vbsGetPrivileges
    set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
    setlocal EnableDelayedExpansion

    :CheckIfRunningAsAdmin
    net session >nul 2>&1
    if %ERRORLEVEL% == 0 ( 
        goto gotPrivileges 
    ) else ( goto ElevatePermissions )

    :ElevatePermissions
    if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
    ECHO args = "ELEV " >> "%vbsGetPrivileges%"
    ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
    ECHO args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
    ECHO Next >> "%vbsGetPrivileges%"
    ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
    "%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*
    exit /B

    :gotPrivileges
    setlocal & pushd .
    cd /d %~dp0
    if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)
    net session >nul 2>&1
    if %ERRORLEVEL% == 0 (
        goto Continue
    ) else (
        REM unable to elevate permissions so tell user to run file as admin manually
        echo Please re-run this file as administrator. Press any key to exit...
        pause > nul
        goto Exit
     )

    :Continue
    <insert rest of code here>