如何在 powershell 中只显示本地地址和 PID?

How can i show only local address and PID in powershell?

 (netstat -ano) -replace '0\.0\.0\.0:(\d+)','        '

what i want is to show only local address and pid using above code

  Proto  Local Address          Foreign Address        State           PID
  TCP    135                    0                      LISTENING       1172
  TCP    445                    0                      LISTENING       4
  TCP    5040                   0                      LISTENING       7300
  TCP    5357                   0                      LISTENING       4
  TCP    7680                   0                      LISTENING       14100
  TCP    49664                  0                      LISTENING       988
  TCP    49665                  0                      LISTENING       896
  TCP    49666                  0                      LISTENING       1724
  TCP    49667                  0                      LISTENING       1472
  TCP    49668                  0                      LISTENING       3520
  TCP    49728                  0                      LISTENING       968

but what i want

Local Address             PID
135                       1172
445                       4
5040                      7300
.                         .
.                         .
.                         .

要在 Powershell 中按列 headers 获取您请求的输出,您可以使用:

Get-NetTCPConnection | 
  Select-Object LocalAddress, OwningProcess | 
  Sort-Object LocalAddress, OwningProcess

您的示例数据似乎显示端口而不是地址,因此:

Get-NetTCPConnection | 
  Select-Object LocalPort, OwningProcess | 
  Sort-Object LocalPort, OwningProcess

如果您还需要 UDP 连接,请将上面的 Get-NetTCPConnection 替换为 Get-NetUDPEndpoint

最后,如果您想要全部:

(Get-NetUDPEndpoint |
    Select-Object @{L="Proto"; E={"TCP"}}, LocalAddress, LocalPort, OwningProcess
) + (Get-NetTCPConnection |
    Select-Object @{L="Proto"; E={"UDP"}}, LocalAddress, LocalPort, OwningProcess
) |
    Sort-Object Proto, LocalPort, LocalAddress

这会如你所愿吗?我假设“本地地址”是指端口号,“PID”是指拥有的进程 ID。如果可以避免,我不想重命名它们。

Get-NetTCPConnection |
    Where-Object { $_.LocalAddress -notmatch '^(127\..*|192\..*|0\..*|::$)' } |
    Select-Object -Property @{n='LocalAddress';e={$_.LocalPort}},@{n='PID';e={$_.OwningProcess}} |
    Sort-Object -Property LocalAddress

您已经获得了所需的信息,现在只需 trim 使用讨厌的正则表达式循环去除多余的属性?可能需要一些间距调整

 (netstat -ano) `
  -replace '0\.0\.0\.0:(\d+)','        '|
  foreach{
    Write-host `
     -nonewline "$([regex]::split("$_",'\s\s+')[2,5])`r`n"
  }

为了可读性,我使用了重音符号(poweshell 转义键)来转义换行符| 将通过管道传递到下一行出现的任何内容