相关文章推荐

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 "0.0.0.0" -and $_.RemoteAddress -notlike "127.0.0.1" -and $_.RemoteAddress -notlike "::")} ' 
    | Get-Unique -AsString | ForEach-Object {
        $hostname = Resolve-DnsName $_.RemoteAddress -ErrorAction SilentlyContinue
        [PSCustomObject]@{
            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 {@('0.0.0.0','127.0.0.1', '::') -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:

Sort IPv4 Addresses Correctly

In the previous tip we published a super-fast function called Test-OnlineFast, and this function was able to ping an entire IP segment in record time: PS> $iprange

@Rob,

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.

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.

 
推荐文章