0

I have no previous batch scripting knowledge. So the question could sound a bit silly. My target is to kill a process listening on a specific port.

I will pass the port number in the batch script argument.

@echo off
netstat -ano | findstr %1

This returns as follow:-

TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       23708
TCP    [::]:8080              [::]:0                 LISTENING       23708

So if do it in the same script as :

taskkill /pid 23708 /F 

It should kill the process. I don't know how to get the pid list in an array. How do I do it?

masiboo
  • 4,537
  • 9
  • 75
  • 136
  • 1
    You should `...|find ":%1 "` instead of `...|findstr %1` to avoid false positives. – Stephan Jul 11 '19 at 17:47
  • Just do this in your script: `FOR /F "Tokens=5" %%A IN ('netstat -ano ^| findstr /I "0\.0\.0\.0:%1 " "\[::\]:%1 "') DO ( Taskkill /pid %%A /F)` That will do the needful. – Ben Personick Jul 11 '19 at 21:10
  • Or since you probably don;t want to only look for listening ports, and you probably do want to limit yourself to TCP you could use this: `FOR /F "Tokens=5" %%A IN ('netstat -ano -p TCP ^| findstr /I ":%1 "') DO ( Taskkill /pid %%A /F)` – Ben Personick Jul 11 '19 at 21:25

0 Answers0