Terminate a Process by Port Number

Terminate a Process by Port Number

A Windows batch file that finds and terminates the process listening on a given TCP/IP network port number


When to use this batch file

This batch file may be helpful when you want to:

  • Stop a program listening on a specific network port, to prevent it from processing additional requests;

  • Restart a network server application and ensure that its listening port will be available for the new instance.


Command line interface

terminate-process-by-port.bat [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.


Return/exit codes

The batch file returns:
  • 0 on success (when there is no process listening on the port or the process listening on the port was closed successfully);

  • 1 if the process listening on the port could not be closed.


Details

Here 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

Compatibility

This batch file has been tested on the following operating systems:

  • Windows 11

  • Windows 10

  • Windows Server 2022

  • Windows Server 2019


History/changes

  • February 15 2023: Initial release.