Techibee.com

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:

Hope this helps and happy learning.

Exit mobile version