Kill TCP connection with Powershell

Sometimes you have an application that keeps connections open while they should be closed.
Because Windows does not seem to have the capability to kill an connection without killing the whole process we’ll to use a 3rd party tool called cports.exe. Download here: https://www.nirsoft.net/utils/cports-x64.zip

 

$ProcessName= "BackgroundTransferHost"
$State = "CloseWait "
while ($true) {

sleep -Seconds 20
$id = (Get-Process $ProcessName).Id

Get-NetTCPConnection -OwningProcess $id -State $State | % {

.\cports.exe /close * * $_.RemoteAddress $_.RemotePort

}

}

One thought to “Kill TCP connection with Powershell”

Leave a Reply

Your email address will not be published. Required fields are marked *