Test connection to servers on several ports

Below you can find simple function to test connection on several ports. Sometimes you had to check connectivity in your environment to all servers. This script will make it easy for you.

Script use Test-NetConnection command which allows to specify port number for checking:

Test-NetConnection -ComputerName DC01  -Port 80 
Test-NetConnection
Test-NetConnection

For more information about this command please refer to technet site.

Usage:

Test-PortConnection -Destination DC01 -Ports 363
Test-PortConnection -Destination DC01 -Ports 363,80,1433
Test-PortConnection -Destination DC01,DC02 -Ports 363,80,1433
Test-PortConnection -Destination DC01,DC02 -Ports 363,80 | Export-Csv -Path C:\users\$env:username\desktop\results.csv -NoTypeInformation # Save it to CSV file on your desktop
Test-PortConnection -Destination (GC "C:\Temp\Servers.txt") -Ports 363,80,1433
Test-PortConnection -Destination (GC "C:\Temp\Servers.txt") -Ports 363,80,1433 | Out-GridView -Title "Results" # Display in new pop-up window

Output:

Test-PortConnection
Test-PortConnection

Final script:


 Function Test-PortConnection {
    [CmdletBinding()]
             
    # Parameters used in this function
    Param
    (
        [Parameter(Position=0, Mandatory = $True, HelpMessage="Provide destination source", ValueFromPipeline = $true)] 
        $Destination,

        [Parameter(Position=1, Mandatory = $False, HelpMessage="Provide port numbers", ValueFromPipeline = $true)] 
        $Ports = "80"
    ) 
     
    $ErrorActionPreference = "SilentlyContinue"
    $Results = @()

    ForEach($D in $Destination)
    {
        # Create a custom object 
        $Object = New-Object PSCustomObject
        $Object | Add-Member -MemberType NoteProperty -Name "Destination" -Value $D


        Write-Verbose "Checking $D" -ForegroundColor Yellow
        ForEach ($P in $Ports)
        {
            $Result = (Test-NetConnection -Port $p -ComputerName $D ).PingSucceeded  
         
            If(!$Result)
            {
                $Status = "Failure"
            }
            Else
            {
                $Status = "Success"
            }

            $Object | Add-Member Noteproperty "$("Port " + "$p")" -Value "$($status)" 
        }

        $Results += $Object 

<# or easier way true/false value
        ForEach ($P in $Ports)
        {
            $Result = $null
            $Result = Test-NetConnection -Port $p -ComputerName $D  
            $Object | Add-Member Noteproperty "$("Port " + "$p")" -Value "$($Result)" 
        }

        $Results += $Object 
#>
    }

# Final results displayed in new pop-up window
If($Results)
{
    $Results
}
} 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.