Test open TCP ports with PowerShell

Home » Codebase » Test open TCP ports with PowerShell

You don’t always need telnet to test if a TCP port is open, PowerShell offers the Test-NetConnection cmdlet which has this option. The cmdlet also has a -Quiet parameter returning only $true or $false. This makes the command ideal for scripting and automation and there is no need for Telnet client.

The Test-NetConnection cmdlet displays diagnostic information for a connection. It supports ping test, TCP test, route tracing, and route selection diagnostics. Depending on the input parameters, the output can include the DNS lookup results, a list of IP interfaces, IPsec rules, route/source address selection results, and/or confirmation of connection establishment.

A quicky to test if GMail’s SMTP port is opened is:

Test-NetConnection -ComputerName smtp.gmail.com -Port 25

ComputerName     : smtp.gmail.com
RemoteAddress    : 2a00:1450:4025:401::6d
RemotePort       : 25
InterfaceAlias   : Ethernet
SourceAddress    : <my local IPv6 address>
TcpTestSucceeded : True

So yes, I reached smtp.gmail.com on port 25. You can also test for port 1433 (SQL Server), 3389 (RDP) and so on, making it ideal for scripting. Utilizing the ping connectivity with -Quiet parameter demonstrates it:

PS > if(Test-Connection -Count 1 -ComputerName smtp.gmail.com -Quiet) {
  Test-NetConnection -ComputerName smtp.gmail.com -Port 25
}

More information is available in Microsoft’s Test-NetConnection documentation.

Jan Reilink
Jan Reilink

In my day to day work, I’m a systems administrator – DevOps / SRE and applications manager at Embrace – The Human Cloud. At Embrace we develop, maintain and host social intranets for our clients. Provide digital services and make working more efficient within various sectors.

Want to support me and donate? Use this link: https://www.paypal.com/paypalme/jreilink.

Articles: 155