Author Posts

August 31, 2016 at 7:50 am

$p = Get-Process
$n = Get-NetTCPConnection

$p
$n.owningprocess

$n | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, AppliedSetting, OwningProcess| ConvertTo-Html | out-file C:\Test1.HTML

I would like to add another column "Process Name"(or what ever) and in that I would like to extract the name of the process from get-process.

I feel like I am close just missing some basic understanding. Any help would be great!

foreach ($item in $n.owningprocess)
    {
        if ($p.id -match $n.owningprocess)
        {
          $properties = @{
        Name = ?
        }
        New-Object -TypeName PSObject -Property $properties

    }

August 31, 2016 at 11:41 am

You can do something like this.

$Procs = Get-Process
$TCP = Get-NetTCPConnection

ForEach ($TCPProc in $TCP)
{
    ForEach ($Proc in $Procs)
    {
        If ($($Proc.ID) -eq $($TCPProc.OwningProcess))
        {
            [PSCustomObject]@{Name = $Proc.ProcessName;
                              LocalAddress = $TCPProc.LocalAddress;
                              LocalPort = $TCPProc.LocalPort;
                              RemoteAddress = $TCPProc.RemoteAddress;
                              RemotePort = $TCPProc.RemotePort;
                              State = $TCPProc.State;
                              AppliedSetting = $TCPProc.AppliedSetting;
                              OwningProcess = $TCPProc.OwningProcess}
        }
    }
}

August 31, 2016 at 1:38 pm

Rather than looping through every process for every netconnection, you should leverage a Where clause against Get-Process:

$TCP = Get-NetTCPConnection

$results = ForEach ($TCPProc in $TCP) {

    $process = Get-Process | Where{$_.ID -eq $TCPProc.OwningProcess}
    [PSCustomObject]@{
        Name = $process.ProcessName;
        LocalAddress = $TCPProc.LocalAddress;
        LocalPort = $TCPProc.LocalPort;
        RemoteAddress = $TCPProc.RemoteAddress;
        RemotePort = $TCPProc.RemotePort;
        State = $TCPProc.State;
        AppliedSetting = $TCPProc.AppliedSetting;
        OwningProcess = $TCPProc.OwningProcess
    }
}

$results

August 31, 2016 at 1:44 pm

Or you could even forego any loops or if statements with calculated expression:

$results = Get-NetTCPConnection |
           Select LocalAddress,
                  LocalPort,
                  RemoteAddress,
                  RemotePort,
                  State,
                  AppliedSetting,
                  OwningProcess,
                  @{Name="Name";Expression={Get-Process | Where{$_.ID -eq $TCPProc.OwningProcess} | Select -ExpandProperty Name}}


$results

August 31, 2016 at 5:54 pm

Thank you all for the help! It was only like 2 am at the time of post for me. Had been working for too many hours and forgot about the Where expression!!
Paul Frankovich and Rob Simmers thanks.