≡ Menu

Query list of active TCP connections in Windows using PowerShell

Its small tip that you want to try if you don’t want to use netstat.exe command to get the active TCP connection details on a Windows server.

The System.Net.NetworkInformation.IPGlobalProperties dotnet class will help you get this information in a simple way. We can find connection local address, local port, remote address, remote port, IP address type and state of the connection. The advantage is output is returned in Object format so that you can apply further filters to extract the data you need.

CODE:

Function Get-ActiveTCPConnections {            
[cmdletbinding()]            
param(            
)            
            
try {            
    $TCPProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()            
    $Connections = $TCPProperties.GetActiveTcpConnections()            
    foreach($Connection in $Connections) {            
        if($Connection.LocalEndPoint.AddressFamily -eq "InterNetwork" ) { $IPType = "IPv4" } else { $IPType = "IPv6" }            
        $OutputObj = New-Object -TypeName PSobject            
        $OutputObj | Add-Member -MemberType NoteProperty -Name "LocalAddress" -Value $Connection.LocalEndPoint.Address            
        $OutputObj | Add-Member -MemberType NoteProperty -Name "LocalPort" -Value $Connection.LocalEndPoint.Port            
        $OutputObj | Add-Member -MemberType NoteProperty -Name "RemoteAddress" -Value $Connection.RemoteEndPoint.Address            
        $OutputObj | Add-Member -MemberType NoteProperty -Name "RemotePort" -Value $Connection.RemoteEndPoint.Port            
        $OutputObj | Add-Member -MemberType NoteProperty -Name "State" -Value $Connection.State            
        $OutputObj | Add-Member -MemberType NoteProperty -Name "IPV4Or6" -Value $IPType            
        $OutputObj            
    }            
            
} catch {            
    Write-Error "Failed to get active connections. $_"            
}           
}

OUTPUT:

TCP-Connections

Hope this helps and happy learning.

{ 4 comments… add one }
  • Saqib August 18, 2015, 7:43 pm

    I am new to powershell and .net coding. I also want to find out the process ID that owns the open connection. What property can I access to get that. Where is the detailed list of properties of GetIPGlobalProperties()?

    • TechiBee August 23, 2015, 9:00 pm

      This class doesn’t return the process IDs. You may want to try parsing “netstat -anob” output

  • Ross April 26, 2016, 10:57 pm

    I usually go with ‘netstat -an | findstr “:80” | findstr “EST” | Measure-Object’ to get the total number of active connections and then ‘netstat -an | findstr “:3389” | findstr “EST” ‘ to provide the IPs of those connections.

Cancel reply

Leave a Comment