Find the PID of a process that uses a port on Windows

前端 未结 7 1208
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 16:58

My service crash on startup with the classic:

java.rmi.server.ExportException: Listen failed on port: 9999

How can I find the process for k

7条回答
  •  萌比男神i
    2020-11-30 17:24

    PowerShell (Core-compatible) one-liner to ease copypaste scenarios:

    netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table
    

    Output:

    ProcessName State     Protocol AddressLocal AddressForeign
    ----------- -----     -------- ------------ --------------
    System      LISTENING TCP      [::]:8080    [::]:0
    System      LISTENING TCP      0.0.0.0:8080 0.0.0.0:0
    

    Same code, developer-friendly:

    $Port = 8080
    
    # Get PID's listening to $Port, as PSObject
    $PidsAtPortString = netstat -aon `
      | Select-String $Port
    $PidsAtPort = $PidsAtPortString `
      | ForEach-Object { `
          $_ -replace '\s+', ',' `
      } `
      | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')
    
    # Enrich port's list with ProcessName data
    $ProcessesAtPort = $PidsAtPort `
      | ForEach-Object { `
        $portProcess = Get-Process `
          | Where-Object Id -eq $_.PID; `
        $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
        Write-Output $_;
      }
    
    # Show output
    $ProcessesAtPort `
      | Sort-Object    ProcessName, State, Protocol, AddressLocal, AddressForeign `
      | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign `
      | Format-Table
    

提交回复
热议问题