PowerShell:Get-NetTCPConnection 脚本也显示用户名和进程名

luc*_*212 5 windows powershell netstat

我创建了一个脚本来输出Get-NetTCPConnection数据,但另外显示Process NameUsername。该脚本确实有效,但我喜欢任何简化或使其更规范的提示。

我想知道是否有更有效的方法将ProcessName和添加Username到输出中,而无需将值预加载到自定义 PSObject ($obj数组)中。我担心自定义e={($obj |? PID -eq $_.OwningProcess | select -ExpandProperty UserName)}}表达式过于复杂。

$obj=@()

Foreach($p In (Get-Process -IncludeUserName | where {$_.UserName} | `
  select Id, ProcessName, UserName)) {
      $properties = @{ 'PID'=$p.Id;
                       'ProcessName'=$p.ProcessName;
                       'UserName'=$p.UserName;
                     }
      $psobj = New-Object -TypeName psobject -Property $properties
      $obj+=$psobj
  }

Get-NetTCPConnection | where {$_.State -eq "Established"} | select `
  RemoteAddress, `
  RemotePort, `
  @{n="PID";e={$_.OwningProcess}}, @{n="ProcessName";e={($obj |? PID -eq $_.OwningProcess | select -ExpandProperty ProcessName)}}, `
  @{n="UserName";e={($obj |? PID -eq $_.OwningProcess | select -ExpandProperty UserName)}} |
  sort -Property ProcessName, UserName |
  ft -auto
Run Code Online (Sandbox Code Playgroud)

这是带有一些示例输出的屏幕截图:

截屏

小智 12

get-nettcpconnection | select local*,remote*,state,@{Name="Process";Expression={(Get-Process -Id $_.OwningProcess).ProcessName}}
Run Code Online (Sandbox Code Playgroud)

我不能相信这个解决方案,我在这里找到它: https: //superuser.com/questions/1215093/powershell-one-liner-to-show-process-on-same-line-as-port-using -netstat-问题/1215237


Avn*_*ner 2

我在 Code Review 中找不到这个问题,所以我暂时在这里发布答案。

使用字典(哈希表)可以简化表达式并缩短每个 pid 的查找时间。

$dict=@{}

Foreach($p In (Get-Process -IncludeUserName | where {$_.UserName -ne $null} | `
  select Id, ProcessName, UserName)) {
      $properties = @{ 'PID'=$p.Id;
                       'ProcessName'=$p.ProcessName;
                       'UserName'=$p.UserName;
                     }
      $psobj = New-Object -TypeName psobject -Property $properties
      $dict[$p.Id] = $psObj

  }

Get-NetTCPConnection | where {$_.State -eq "Established"} | select `
  RemoteAddress, `
  RemotePort, ` 
  @{n="PID";e={$_.OwningProcess}}, 
  @{n="ProcessName";e={ $dict[[int]$_.OwningProcess].ProcessName }}, `
  @{n="UserName"; e={ $dict[[int]$_.OwningProcess].UserName }} |
  sort -Property ProcessName, UserName | ft -auto
Run Code Online (Sandbox Code Playgroud)