Get-NetTCPConnection vs Netstat

Hey all, I am writing a script that I am planning on doing a blog about shortly. I have run into a potential issue and would like this group’s feedback on. So here’s the deal. As part of this script, I am getting all of the connections to the target server. Using NetStat I see the connections that I expect, i.e. the DB server connection. When I use Get-NetTCPConnection I don’t see this connection. Below is a snippet of code that I am using for the NetTCPConnection piece. Am I overlooking something that is causing this to drop off the report?

$targetserver = Read-Host "Enter Target Server Name"
    Get-NetTCPConnection -CimSession (New-CimSession -Name $targetserver) | Select-Object RemoteAddress | Sort-Object RemoteAddress | `
    Where-Object {($_.RemoteAddress -NotLike "" -and $_.RemoteAddress -notlike "" -and $_.RemoteAddress -notlike "::")} ' 
    | Get-Unique -AsString | ForEach-Object {
        $hostname = Resolve-DnsName $_.RemoteAddress -ErrorAction SilentlyContinue
            IPAddress = $_.RemoteAddress
            Hostname = $hostname.NameHost
    } | Format-Table -AutoSize
    Get-CimSession | Remove-CimSession

The first thing would be to validate you are indeed looking at the remote system and not local with both commands. Do you get the same results if you run it locally on the system in question vs remote connections? Do you see the connection with no filters? Also, simplified code:

Get-NetTCPConnection -CimSession (New-CimSession -Name $targetserver) | 
Where-Object {@('','', '::') -notcontains $_.RemoteAddress} |
Sort-Object -Property {$_.RemoteAddress -as [Version]} -Unique |
Select-Object -Property @{Name='IPAddress';Expression={$_.RemoteAddress}}, 
                        @{Name='HostName';Expression={Resolve-DnsName $_.RemoteAddress}}

IP addresses won’t sort right, so you can do a conversion to Version:


Yes. I am getting the same results locally on the server as I am remotely. Even just running get-nettcpconnection locally on the server, I am not seeing the DB server connection.

SN: I appreciate the reduced code. I am reviewing it now, Thank you.

There are some projects out there that specifically try to replace netstat:

Assuming you are looking for a TCP, not UDP or different protocol it should show up, but you can try the above to see if it matches netstat output. I’ve used Get-NetTCPConnection to find SQL connections, something like:

Get-NetTCPConnection -RemotePort 1433 -State Established

It’s difficult to provide any additional insight unless you post what you are actually seeing in NETSTAT vs Get-NetTcpConnection.