问题
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!
回答1:
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
回答2:
@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
来源:https://stackoverflow.com/questions/24651229/how-to-query-netstat-to-find-pid-for-specific-local-address-in-windows-7