PowerShell: Check If Port is Open – Test TCP Connection

During troubleshooting of different issues it is often required to check if some TCP port on a remote host is opened and ensure that it is not blocked by a firewall.

The most common tool for this is telnet, but it may not be installed or you may want to be able to copy the output to paste it into a ticket or to send it someone, that is not always possible with telnet.

Also the telnet command is not very handy if you need to check connectivity to multiple hosts/ports, but you can do this easily with a PowerShell.

In Windows, you can test connection to TCP port from the command line using PowerShell and in this note i will show how to do this.

Cool Tip: How to install telnet in Windows! Read more →

Test Connection to Port using PowerShell

Use one of the following PowerShell commands to check if TCP port on a remote host is opened:

PS C:\> tnc www.shellhacks.com -Port 443

– or –

PS C:\> New-Object System.Net.Sockets.TcpClient("www.shellhacks.com", 443)

Check open ports on multiple hosts

If you need to test multiple TCP connections, list the required destinations and copy/paste the script into the PowerShell console:

PS C:\> @"
        # List of hosts and ports to check
        "@.split("`n") | ForEach-Object {
            $server,$port = $_.split(':')
            echo "Host: $_"
            New-Object System.Net.Sockets.TcpClient("$server", $port) | 
            Out-String -Stream | Select-String "Connected"
Was it useful? Share this post with the world!

5 Replies to “PowerShell: Check If Port is Open – Test TCP Connection”

  1. Also u can use tnc command in Windows 10 PowerShell:

    PS C:\> tnc HOST_NAME -port PORT_NUMBER
    1. Thanks. Added to the article.

  2. What is the variable to check programmatically afterwards?
    $? seems to be always True

    1. The output of tnc HOST_NAME -port PORT_NUMBER by default exports an object with several items. I think what you’re looking for is $_.TcpTestSucceeded

  3. I think it would be appropriate to say what ‘tnc’ is (Test-NetConnection).
    “@.split(“`n”) | ForEach-Object {
    $server,$port = $_.split(‘:’); write-host “serv: $server, port $port”
    echo “Host: $_”
    New-Object System.Net.Sockets.TcpClient(“$server”, $port) | Out-String -Stream | Select-String “Connected”
    Test-NetConnection -ComputerName $server -Port $port | Out-String -Stream | Select-String “TcpTestSucceeded”

    Why did you use quotes around $server?
    Appreciate the various coding techniques/syntax to accomplish something – we learn more than just an answer to the problem.

Leave a Reply