@ECHO OFF :: =========================================================================== :: This script terminates the process listening on a local address with a :: given port number. :: The port number can be passed on the command line. It defaults to 80 if :: not provided. :: Exits with 0 on success, 1 on failure. :: :: Usage: :: terminate-process-by-port [port-number] :: where :: [port-number] is the port number on which the application you wish to :: terminate is listening. Note that the port number defaults to 80 :: (i.e. the HTTP port) if not specified on the command line. :: :: Created by Core Technologies Consulting, LLC :: https://www.coretechnologies.com/ :: =========================================================================== SET portNumber=80 IF "%1" NEQ "" SET portNumber=%1 SET pid= :: Find the ID of the process listening on the local address with the given port. FOR /F "tokens=5 delims= " %%P in ('netstat -ano -p tcp ^| findstr /r /c:":%portNumber% *[^ ]*:[^ ]* "') DO SET pid=%%P :: Done if no process was found. IF "%pid%" == "" ( ECHO There is no process listening on port %portNumber%. Exiting with 0. EXIT /B 0 ) :: Treminate the process (and any child processes it started). ECHO Found process %pid% listening on port %portNumber%. Terminating it. TASKKILL /F /T /PID %pid% :: Unfortunately TASKKILL doesn't let us know if the process was killed or not. :: Check if it's still alive and echo the outcome. SET pid2= FOR /F "tokens=5 delims= " %%P in ('netstat -ano -p tcp ^| findstr /r /c:":%portNumber% *[^ ]*:[^ ]* "') DO SET pid2=%%P IF "%pid2%" EQU "" ( ECHO Process %pid% has been terminated. Exiting with 0. EXIT /B 0 ) IF "%pid2%" EQU "%pid%" ( ECHO Failed to terminate process %pid%! Exiting with 1. EXIT /B 1 ) ECHO Terminated process %pid% but process %pid2% stole the port! Exiting with 1. EXIT /B 1