Get TCP/UDP Connection Count

Adam Bertram

Adam Bertram

Read more posts by this author.

I’ve been troubleshooting an intermittent problem with a Windows 2008 R2 server for a few weeks now. I opened a Microsoft support ticket and the problem was believed to be due to port exhaustion in the dynamic port range.

I confirmed the max ports were at 16,184 which was the default at the command prompt.

> netsh int ipv4 show dynamicport tcp
> netsh int ipv4 show dynamicport udp

I then needed a quick way to test this so I came up with this simple script. I had to use the CLI utility netstat because this server does not have PowerShell v4 on it else I would have used Get-NetTCPConnection.

I figured I’d share to save someone a little bit of time figuring out how to get the TCP/UDP connection count on a remote server.

$Server = 'SERVER'
$TcpCount = Invoke-Command -Computername $Server -ScriptBlock {(netstat -an | Where-Object {($_ -notmatch 'LISTENING') -and ($_ -match '^  TCP')}).Count}
$UdpCount = Invoke-Command -Computername $Server -ScriptBlock {(netstat -an | Where-Object {($_ -notmatch 'LISTENING') -and ($_ -match '^  UDP')}).Count}
Write-Output "TCP count is $TcpCount and UDP count is $UdpCount on server $Server"

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!