Search code examples
batch-filetaskkill

Search for and kill PIDs, one at a time


I have the following command that works pretty well:

FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| grep :7010') DO TaskKill.exe /PID %%P /F

The issue is, if the same port is found multiple times with the same PID, my script returns errno 1 because the attempts to kill the PID after the first have failed.

Is there a way to modify the above so that it only attempts to kill the PID once?


Solution

  • this might work for you:

    @ECHO OFF &SETLOCAL disableDelayedExpansion
    FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| grep :7010') DO (
        IF NOT DEFINED PID.%%P (
            TASKKILL.exe /PID %%P /F
            SET "PID.%%P=7"
        )
    )