Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

High-Performance Network Auditing: Custom Ping and TCP Port Testing in PowerShell .Net Objects

This article dives into the Test-TcpPort function, a compact script that resolves hostnames to IPs, pings for basic reachability, and tests port connectivity with a timeout. I will break down its mechanics in short. At its core, Test-TcpPort leverages .NET's System.Net and System.Net.Sockets namespaces for low-level networking checks, wrapped in PowerShell's object-oriented paradigm. Here's the full code for reference:

 function Test-TcpPort {
    param (
        [parameter(Mandatory)][String]$ComputerName,
        [parameter(Mandatory)][Int]$Port,
        [parameter(Mandatory=$false)][Int]$ConnectionTimeout = 500 # Timeout in milliseconds
    )
    try
    {
        $hostEntry = [System.Net.Dns]::GetHostAddresses($ComputerName)
        $ip = ($hostEntry | Where-Object AddressFamily -eq 'InterNetwork').IPAddressToString
    }
    catch
    {
        $ip = $ComputerName
    }
    try
    {
        $ping = New-Object System.Net.NetworkInformation.Ping
        $pingReply = $ping.Send($ip)
        if ($pingReply.Status -eq 'Success')
        {
            $pingStatus = $true
        }
        else {
            $pingStatus = $false
        }
    }
    catch
    {
        $pingStatus = $false
    }
    $tcpClient = New-Object System.Net.Sockets.TcpClient
    $portConnectionStatus = $false
    try {
        $connectAsync = $tcpClient.BeginConnect($ip, $Port, $null, $null)
        $waitHandle = $connectAsync.AsyncWaitHandle
        if ($waitHandle.WaitOne($ConnectionTimeout, $false)) {
            $tcpClient.EndConnect($connectAsync)
            $portConnectionStatus = $true
        }
    }
    finally {
        $tcpClient.Close()
        $waitHandle.Dispose()
    }
    $result = [pscustomobject]@{
       ComputerName = $ComputerName
       IP = $ip
       PingStatus = $pingStatus
       PortConnectionStatus = $portConnectionStatus
    }
    return $result
}

$computers = "ad001", "server1", "psdomain02", "192.168.34.39"
$computers | ForEach-Object {Test-TcpPort -ComputerName $_ -Port 445}

This script is way faster than the earlier written article Building a Unified Ping and Port Connectivity Report with PowerShell and Parallel Ping and Port Testing in PowerShell Using Runspaces

In the script:

Step 1: DNS resolution uses [System.Net.Dns]::GetHostAddresses(), filtering for IPv4 (InterNetwork) to grab the first available IP. 
Step 2: Next, it instantiates a Ping object from System.Net.NetworkInformation and sends a single ICMP echo to the resolved IP. Success sets $pingStatus to $true; failures (timeouts, blocks) default to $false.
Step 3: Asynchronous TCP Connection Test - A TcpClient attempts a non-blocking connect via BeginConnect(), paired with an AsyncWaitHandle for timeout enforcement.

Below are the different way you can use and execute function Test-TcpPort.

$computers = "ad001", "server1", "psdomain02", "192.168.34.39"
$computers | ForEach-Object {Test-TcpPort -ComputerName $_ -Port 445}

Get-Content servers.txt | ForEach-Object { Test-TcpPort -ComputerName $_ -Port 443 } | Export-Csv -Path portscan.csv
1..3 | ForEach-Object { Test-TcpPort -ComputerName "target" -Port (22 + $_) } #for sequential ports.

Download this script ping_port_scanner_powershell.ps1 or it is also available on github.com.

Powershell net framework object ping telnet port scanner free tool dns tutorial

It reduces Overhead: Avoids the heavier cmdlets like Test-Connection and Test-NetConnection when you only need basic port checks.

Useful Articles
Executing PowerShell script from PHP HTML web server
Send system disk space utilization HTML report Email using PowerShell
Send Email using PowerShell with .net object System.Net.Mail.MailMessage
PowerShell XML OperationStopped: No coercion operator is defined between types 'System.Object&' and 'System.Object'
Powershell Create new file if not exist, if exist Rename file
PowerShell Create XML document with XmlWriter .net object
PowerShell save export data to XML file
Bulk change multiple file names with OneLiner PowerShell command
Resolved PowerShell Visual studio code stuck with 'Starting up PowerShell' in status bar
Building basic simple Web Server using PowerShell
Running Your First PowerShell Scripts With Jenkins and Git
Git clone or push Missing or invalid credentials fatal authentication failed
PowerShell How to find file and folders in Azure Storage Account Blobs and Containers

Go Back

Comment

Protected by Mathcha

Blog Search

Page Views

1 4 6 4 5 8 3 9

Archive

Follow me on Blogarama