A Windows batch file that finds and terminates the process listening on a given TCP/IP network port numberWhen to use this batch fileThis batch file may be helpful when you want to:
Command line interface
terminate-process-by-port.bat [port-number] where:
Return/exit codesThe batch file returns:
DetailsHere are the full contents of the batch file (click the button to download): @ECHO OFF REM =========================================================================== REM This script terminates the process listening on a local address with a REM given port number. REM The port number can be passed on the command line. It defaults to 80 if REM not provided. REM Exits with 0 on success, 1 on failure. REM REM Created by Core Technologies Consulting, LLC REM https://www.coretechnologies.com/ REM =========================================================================== SET portNumber=80 IF "%1" NEQ "" SET portNumber=%1 SET pid= REM 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 REM Done if no process was found. IF "%pid%" == "" ( ECHO There is no process listening on port %portNumber%. Exiting with 0. EXIT /B 0 ) REM Treminate the process (and any child processes it started). ECHO Found process %pid% listening on port %portNumber%. Terminating it. TASKKILL /F /T /PID %pid% REM Unfortunately TASKKILL doesn't let us know if the process was killed or not. REM 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 CompatibilityThis batch file has been tested on the following operating systems:
History/changes
|