Testing TCP Connections with PowerShell

Sometimes you may need to test if you can establish a TCP connection to an endpoint, there are many ways you can achieve this, in this article we will be using PowerShell.

Why PowerShell?

Well why not? I personally like PowerShell, possibly because a lot of scripting I do is in Windows environments, I often find myself using PowerShell not only to perform automation tasks like this but to administer a PC. also, PowerShell is able to run on almost all PCs now (Windows, Mac OS & Linux).

The Code

In PowerShell ISE or your preferred code editor paste the following code:
you can edit the code to meet your requirements.

# a simple array of URLs / IP Addresses
$ipaddress =@("site1",
                "site2",")
#set the TCP Port Number to test the connection to
$port = 443
#Start the For Each Loop
Foreach ($i in $ipaddress) {
#echo the site / IP that is being tested
    Write-host "Testing $i"
#test the connection
    $connection = New-Object System.Net.Sockets.TcpClient($i, $port)
    if ($connection.Connected) {
       Write-Host "Successfully connected to $i on port $port" -ForegroundColor Green
    } else {
        Write-Host "Failed to connect to $i on port $port" -ForegroundColor Red
    }
}

Testing TCP Connections with PowerShell
Scroll to top