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

坚强是说给别人听的谎言 提交于 2019-12-02 03:41:17

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
@echo off

    setlocal enableextensions

    set "port=8080"

    for /f "tokens=1,4,5" %%a in (
        'netstat -aon ^| findstr /r /c:"[TU][CD]P[^[]*\[::\]:%port%"'
    ) do if "%%a"=="UDP" (taskkill /F /PID %%b) else (taskkill /f /PID %%c)

    endlocal

Use findstr to retrieve only the needed record, tokenize it using the for command to get the PID column (4th for UDP, 5th for TCP) and kill the task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!