Test if a port is open with PowerShell

Published on Tuesday, 10 October 2023

You don't always need telnet to test if a 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 could reach 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.