Kill a process that is listening on a network port

Sometimes, you want to forcibly deploy/install a piece of software that requires a particular service port. This script will find any process that is listening on that port and kill it and if it is a windows service, also disable the service.

param([string]$Port = '80')

$a = netstat -a -n -o

$a -split [environment]::NewLine | foreach {
    $parts = $_.Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries) 
    $isMatch = $parts | where {$_ -like "*:$Port*" }
    if($isMatch -and $parts[3] -like 'LISTENING') {
        $proc = Get-Process -Id $parts[4] -ErrorAction SilentlyContinue
        if(-not $proc) {continue}
        Write-Warning "A process was found listening on port $($parts[4])"
        $foundService = (Get-WmiObject Win32_Service -Filter "ProcessId='$($parts[4])'") 
        if($foundService) {
            Write-Host "The process was running as a service, the service will be stopped and disabled ($($foundService.PathName))"
            [void]$foundService.StopService()
            [void]$foundService.ChangeStartMode("disabled")
        }

        Write-Host "Killing process $($proc.Name)"
        kill -Id $parts[4] -Force
        $s = Get-Service
    }
}


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s