Solved

pipeline netstat with tasklist

Posted on 2014-01-30
4
897 Views
Last Modified: 2014-01-31
I have two commands I want to serialize and output a list of ports mapped to services, using the PID column. Specifically, the "Local Address" column from netstat -ano would pair nicely with the "Image Name" column from the tasklist /svc command.

Would you help me understand how to link these two commands where the output pairs "Local Address" with "Image Name", keyed off the common PID column from each command?

Thanks!
JohnD
0
Comment
Question by:johndarby
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 40

Accepted Solution

by:
footech earned 250 total points
ID: 39823408
Thought this was kind of interesting.  I modified the code found at http://poshcode.org/2701 to add a -svc switch parameter to the function which will display some info about associated services.

function Get-NetworkStatistics
{
        [OutputType('System.Management.Automation.PSObject')]
        [CmdletBinding(DefaultParameterSetName='name')]
           
        param(
                [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='port')]
                [System.Int32]$Port,
                   
                [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='name')]
                [System.String]$ProcessName='*',
                   
                [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='address')]
                [System.String]$Address='*',           
                   
                [Parameter()]
                [ValidateSet('*','tcp','udp')]
                [System.String]$Protocol='*',
     
                [Parameter()]
                [ValidateSet('*','Closed','CloseWait','Closing','DeleteTcb','Established','FinWait1','FinWait2','LastAck','Listen','SynReceived','SynSent','TimeWait','Unknown')]
                [System.String]$State='*',

                [Parameter()]
                [switch]$Svc
                   
        )
       
        begin
        {
                $properties = 'Protocol','LocalAddress','LocalPort'
                $properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'
                if ($Svc)
                {
                    $properties += 'Services'
                    $svclist = Get-WmiObject Win32_Service -filter "ProcessID != 0" | Select Name, ProcessID
                }
        }
           
        process
        {
            netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {
     
                $item = $_.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
     
                if($item[1] -notmatch '^\[::')
                {          
                    if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
                    {
                        $localAddress = $la.IPAddressToString
                        $localPort = $item[1].split('\]:')[-1]
                    }
                    else
                    {
                        $localAddress = $item[1].split(':')[0]
                        $localPort = $item[1].split(':')[-1]
                    }
     
                    if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
                    {
                        $remoteAddress = $ra.IPAddressToString
                        $remotePort = $item[2].split('\]:')[-1]
                    }
                    else
                    {
                        $remoteAddress = $item[2].split(':')[0]
                        $remotePort = $item[2].split(':')[-1]
                    }
                                   
                                $procId = $item[-1]
                                $procName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
                                $proto = $item[0]
                                $status = if($item[0] -eq 'tcp') {$item[3]} else {$null}                               
                                   
                                
                                if ($Svc)
                                {
                                    $pso = New-Object -TypeName PSObject -Property @{
                                            PID = $procId
                                            ProcessName = $procName
                                            Protocol = $proto
                                            LocalAddress = $localAddress
                                            LocalPort = $localPort
                                            RemoteAddress = $remoteAddress
                                            RemotePort = $remotePort
                                            State = $status
                                            Services = ($svclist | Where { $_.ProcessID -eq $procId } | Select -ExpandProperty Name) -join ", "
                                    } | Select-Object -Property $properties
                                }
                                else
                                {
                                    $pso = New-Object -TypeName PSObject -Property @{
                                            PID = $procId
                                            ProcessName = $procName
                                            Protocol = $proto
                                            LocalAddress = $localAddress
                                            LocalPort = $localPort
                                            RemoteAddress = $remoteAddress
                                            RemotePort = $remotePort
                                            State = $status
                                    } | Select-Object -Property $properties
                                }
     
     
                                if($PSCmdlet.ParameterSetName -eq 'port')
                                {
                                        if($pso.RemotePort -like $Port -or $pso.LocalPort -like $Port)
                                        {
                                            if($pso.Protocol -like $Protocol -and $pso.State -like $State)
                                                {
                                                        $pso
                                                }
                                        }
                                }
     
                                if($PSCmdlet.ParameterSetName -eq 'address')
                                {
                                        if($pso.RemoteAddress -like $Address -or $pso.LocalAddress -like $Address)
                                        {
                                            if($pso.Protocol -like $Protocol -and $pso.State -like $State)
                                                {
                                                        $pso
                                                }
                                        }
                                }
                                   
                                if($PSCmdlet.ParameterSetName -eq 'name')
                                {              
                                        if($pso.ProcessName -like $ProcessName)
                                        {
                                                if($pso.Protocol -like $Protocol -and $pso.State -like $State)
                                                {
                                                        $pso
                                                }
                                        }
                                }
                }
            }
        }
<#
     
.SYNOPSIS
        Displays the current TCP/IP connections.
     
.DESCRIPTION
        Displays active TCP connections and includes the process ID (PID) and Name for each connection.
        If the port is not yet established, the port number is shown as an asterisk (*).       
           
.PARAMETER ProcessName
        Gets connections by the name of the process. The default value is '*'.
           
.PARAMETER Port
        The port number of the local computer or remote computer. The default value is '*'.
     
.PARAMETER Address
        Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
     
.PARAMETER Protocol
        The name of the protocol (TCP or UDP). The default value is '*' (all)
           
.PARAMETER State
        Indicates the state of a TCP connection. The possible states are as follows:
                   
        Closed          - The TCP connection is closed.
        CloseWait       - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
        Closing         - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
        DeleteTcb       - The transmission control buffer (TCB) for the TCP connection is being deleted.
        Established     - The TCP handshake is complete. The connection has been established and data can be sent.
        FinWait1        - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
        FinWait2        - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
        LastAck         - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
        Listen          - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
        SynReceived     - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
        SynSent         - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
        TimeWait        - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
        Unknown         - The TCP connection state is unknown.
           
        Values are based on the TcpState Enumeration:
        http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
     
.EXAMPLE
        Get-NetworkStatistics
     
.EXAMPLE
        Get-NetworkStatistics iexplore
     
.EXAMPLE
        Get-NetworkStatistics -ProcessName md* -Protocol tcp
     
.EXAMPLE
        Get-NetworkStatistics -Address 192* -State LISTENING
     
.EXAMPLE
        Get-NetworkStatistics -State LISTENING -Protocol tcp
     
.EXAMPLE
        Get-NetworkStatistics -Svc

.OUTPUTS
        System.Management.Automation.PSObject
     
.NOTES
        Based off work by: Shay Levy
        Blog  : http://PowerShay.com
#>     
}
     
help Get-NetworkStatistics

Open in new window

It outputs PsObjects, so you can customize which properties you want to display, etc.  Here's an example.
Get-NetworkStatistics -svc | select protocol,localport,processname,pid,services | sort localport -Unique | ft -auto -Wrap

Open in new window

0
 
LVL 70

Assisted Solution

by:Qlemo
Qlemo earned 250 total points
ID: 39823425
Instead of using netstat -ano, it might be easier to use www.sysinternals.com' TcpVCon -ac, which output as CSV is much easier to process.

Do you want to get the complete list, or ask for a specific service or process?
0
 
LVL 40

Expert Comment

by:footech
ID: 39823578
@Qlemo -  :)  I had thought of that.  If I was starting out from scratch I would probably use that output instead, but since someone had already done the work of parsing netstat I just added on to that.
0
 
LVL 1

Author Closing Comment

by:johndarby
ID: 39824179
Thanks guys; I think I will write a custom app in C# to do the job; I want to hand off something portable to my guys in the lab; thank you!
0

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A brief introduction to what I consider to be the best editor for PowerShell.
My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

624 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question