PowerShell(与Core兼容)的一线式可简化复制粘贴的情况:
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
输出:
ProcessName State Protocol AddressLocal AddressForeign
----------- ----- -------- ------------ --------------
System LISTENING TCP [::]:8080 [::]:0
System LISTENING TCP 0.0.0.0:8080 0.0.0.0:0
相同的代码,对开发人员友好:
$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