3

I want to list and kill all processes belonging to a session of a particular process that is using a port. This should happen through a windows batch command that would accept a port number as input.

For example: Let us say a process PA is currently listening on port 8081. PA is running under the session S1 There are processes PB and PC belonging to same session as PA. PB and PC will be running on different ports(It is not important which ports they are running on)

The windows command/batch file should take 8081 as input and kill the processes PA, PB and PC.

Is this possible? Appreciate a little help on this as I am not really well versed in batch commands/scripting.

My Failed attempt:

(for /F "tokens=2" %%i in (for /f "tokens=5" %a in ('netstat -aon ^| findstr 8081') do tasklist /NH /FI "PID eq %a") do taskkill /NH /FI "SESSIONNAME eq %%i")

3 Answers3

5

That's actually pretty easy in PowerShell:

# Get the process of the listening NetTCPConnection and the session ID of the process
$SessionId = (Get-Process -Id (Get-NetTCPConnection -State Listen -LocalPort 8081).OwningProcess).SessionId
# Get all processes from that session and stop them
Get-Process | Where-Object { $_.SessionId -eq $SessionId } | 
    Stop-Process -Force -Confirm:$false
Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89
1

If you are looking for batch script

for /f "tokens=5" %%a in ('netstat -aon ^| findstr 8081 ^| findstr "LISTEN"') do (
    for /f "tokens=3" %%b in ('tasklist /NH /FI "PID eq %%a"') do (
        for /f "tokens=2" %%c in ('tasklist /NH /FI "SESSIONNAME eq %%b"') do (
            taskkill /F /PID %%c
        )
    )
)
Vazid
  • 111
  • 2
0

You can make a function from this:

function kpn($port){ps|?{$_.sessionID-eq(get-NetTcpConnection -sta listen -loc $port)}|kill -fo -confirm:$false}

And call it like

kpn(8081)
Wasif
  • 321
  • 2
  • 8