skip to Main Content

I need to kill a process which does not list when I use the netstat command. The following command will find the process id of 4 which is not the one that I am looking for.

    $processPID =  $($(netstat -aon | findstr '5000')[0] -split 's+')[-1]
    Stop-Process $processPID

I know the process that I need is in the results of the following.

Get-Process -Name dotnet

And I can’t find a way to use the Get-Process to use with the port filter. For the information of dotnet people, I am running the project using the dotnet CLI command from powershell.

In the screenshot below, you can see the process id for the process listening on port
5100

enter image description here

3

Answers


  1. Chosen as BEST ANSWER

    Thanks to @Mathias and @Sebastian. With your valuable inputs I came up with the following function to get the process id.

        function Get-ProcessByPort {
        param(
            [int]$Port
        )
        $services = netsh http show servicestate
        $positionSession=0
        $countSession=0
        $countProcess=0
        [bool] $takeNextPID=0
        $processId=$null
        foreach ($s in $services){
            if ($takeNextPID -eq 1) {
                $processId=$s
                break
            }
            if ($s -match 'Server session ID') {
                $countSession++
            }
            if ($s -match "HTTP://LOCALHOST:$Port/") {
                $positionSession=$countSession
            }
            if ($s -match 'Process IDs:') {
                $countProcess++
            }
            if ($positionSession -gt 0) {
                if ($countProcess -eq $positionSession) {
                    $takeNextPID=1
                }
            }
        }
        if (-not ([string]::IsNullOrEmpty($processId)))
        {
            $processId=$processId.Trim()
        }   
        return $processId
    }
    

  2. Use the Get-NetTCPConnection cmdlet to get the same output as netstat, but as structured objects instead of text:

    Get-NetTCPConnect -LocalPort 5000 |Get-Process -Id {$_.OwningProcess} -IncludeUsername:$false
    
    Login or Signup to reply.
  3. As above, here’s a function for getting the PID depending if this is either a LocalPort or RemotePort.

    function Get-ProcessByPort {
        param(
            [int]$Port,
            [ValidateSet('LocalPort', 'RemotePort')]
            [string]$PortType = 'LocalPort'
        )
    
        $splat = @{
            $PortType = $Port
        }
    
        $processes = Get-NetTCPConnection @splat | Select-Object -ExpandProperty OwningProcess | ForEach-Object { Get-Process -Id $_ } | Select-Object -Unique
        return $processes | Select-Object -ExpandProperty Id
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search