Wednesday, December 17, 2014

Kill a Process by Looking up the Port


Here is command to start
    
FOR /F "tokens=5 delims= " %%P IN ('netstat -ano ^| findstr :8700') DO @ECHO TaskKill.exe /PID %%P /F

After I was confident I have removed ECHO command.

FOR /F "tokens=5 delims= " %%P IN ('netstat -ano ^| findstr :8700') DO TaskKill.exe /PID %%P /F

Here is example how this work.
netstat -ano  will give result in below format.  The Process ID associate with Port 8700 is 2686.
Note 2684 (PID) is 5 column in output.


 

Hence token=5. Run above command and see which column is a Port Number. For some OS like XP this is 4th column. So for XP token=4


"tokens=5 delims= "
This lets you split up each line by whitespace, and take the 5th chunk in that line, and stuffs it into %variable (in our case, %%P). delims looks empty, but that extra space is actually significant.

netstat -ano
Run this command on command prompt and see its usage.

^|
Transfer output from netstat and  passes it to findstr

findstr :8700
This filters any output that is passed into it, returning only lines that contain :8700.

TaskKill.exe /PID

This kills a running task, using the process ID.
%%P instead of %P


This is required in batch files. If you did this on the command prompt, you would use %P instead. This is required in batch files. If you did this on the command prompt, you would use %P instead.