Windows batch file - list listening ports with owning process

How to list each Windows process that is listening on a network port?

Build up the command as follows:

  1. netstat is a most useful Windows command to list network connections and open ports. Generally I use -aon as arguments to list everything and associated process by pid in its output.
  2. use find to filter on the LISTENING status we're interested in
  3. use a for loop to execute that netstat / find output and iterate and process the output
  4. for each line (which corresponds to an open listening port) use tasklist with a filter argument to to turn the pid into some process details for the same.

SO the complete one line cmd as follows

for /f "tokens=2,5" %t in ( 'netstat -aon ^| find "LISTEN"' ) do @for /f %p in ( 'tasklist /fi "pid eq %u" /fo csv /nh' ) do @echo %t %p

OR stick that into a batch file, basically the same just allowing for the now required double %% and split the line for readability

get-listening-ports-and-process.bat

@echo off
for /f "tokens=2,5" %%t in ( 'netstat -aon ^| find "LISTEN"' ) do (
for /f %%p in ( 'tasklist /fi "pid eq %%u" /fo csv /nh' ) do echo %%t %%p
)