PowerShell: Get-NetTCPConnection script that also shows Username & Process Name

luckman212 picture luckman212 · Jun 12, 2017 · Viewed 12.3k times · Source

I created a script to output Get-NetTCPConnection data but additionally show Process Name and Username. The script does work, but I would love any tips to simplify or make this more canonical.

I am wondering if there is a more efficient way to add the ProcessName and Username to the output without having to preload the values into the custom PSObject ($obj array). I am concerned that the custom e={($obj |? PID -eq $_.OwningProcess | select -ExpandProperty UserName)}} expression is overly complex.

$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

Here's a screenshot with some sample output:

screenshot

Answer

MattZ picture MattZ · Feb 20, 2019
get-nettcpconnection | select local*,remote*,state,@{Name="Process";Expression={(Get-Process -Id $_.OwningProcess).ProcessName}}

I can't take credit for this solution, I found it here: https://superuser.com/questions/1215093/powershell-one-liner-to-show-process-on-same-line-as-port-using-netstat-issue/1215237