Kumar
Kumar

Reputation: 3990

Kill multiple process by its port from batch

I want to kill several processes which are listening specific ports (say 2100 and 2101). I can kill a process by its port. But i want to do the same for multiple port(more than one)

Batch Code (Working to kill a port 2100)

FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :2100.*LISTENING') DO taskkill /F /PID %%P

How can i create a command like below (to kill 2100 and 2101)

FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :2100.*LISTENING OR 2101.*LISTENING') DO taskkill /F /PID %%P

Upvotes: 1

Views: 1846

Answers (2)

MC ND
MC ND

Reputation: 70923

For a single digit change

FOR /F "tokens=5" %%P IN ('
    netstat -noa ^| findstr /r /c:":210[01] .*LISTENING"
') DO taskkill /F /PID %%P

For a more complex case with changing numbers (the regexp in findstr does not allow |)

for %%a in (2100 2101) do (
    FOR /F "tokens=5" %%P IN ('
        netstat -noa ^| findstr /r /c:":%%a .*LISTENING"
    ') DO taskkill /F /PID %%P
)

Or, if the list is short (as this case)

FOR /F "tokens=5" %%P IN ('
    netstat -noa 
    ^| findstr /l /c:"LISTENING" 
    ^| findstr /l /c:":2100 " /c:":2101 "
') DO taskkill /F /PID %%P

Upvotes: 2

Magoo
Magoo

Reputation: 79983

FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr ":2100.*LISTENING 2101.*LISTENING"') DO taskkill /F /PID %%P

should work quite happily

Upvotes: 3

Related Questions