Search code examples
windowsbatch-filenetstat

How to query netstat to find PID for specific local address in Windows 7?


I frequently start server on local address [::]:8080. To terminate server I need PID fetched from netstat -aon.

To terminate this server I do taskkill /F /PID <found pid>

I want to create windows batch file that can find PID and apply it in call taskkill /F /PID <found pid>

How can I create such batch file?

Thanks!


Solution

  • On my PC there could be a UDP or TCP connection and they require slightly different code:
    Test this to see if one of the taskkill commands looks right and remove echo to enable the taskkill command.

    @echo off
    for /f "tokens=5" %%a in ('netstat -aon ^|find " [::]:8080 " ^|find /i " TCP " ') do echo taskkill /F /PID %%a
    
    for /f "tokens=4" %%a in ('netstat -aon ^|find " [::]:8080 " ^|find /i " UDP " ') do echo taskkill /F /PID %%a