PowerShell: remotely verify if TCP port is listening

I recall one of the most powerful lessons I learnt on the job was when I learnt how to remotely (or locally – 127.0.0.1) verify if a TCP port was actively listening using the TELNET command. So many ‘Is the firewall open?’ questions answered with a single command

More recently I’ve been in situations where I have a company assigned Windows notebook, with telnet.exe missing and various GPO restrictions in place. However, these notebooks did have PowerShell – so I became curious to determine if I could achieve the same verification as I was with Telnet – Yes you can. Open PowerShell – and use this:
If (New-Object System.Net.Sockets.TCPClient -ArgumentList '<fqdn.domain.tld>',<port-num>) { Write-Host 'YES' } If ($? -eq $false) { Write-Host 'NO' }

Replace <fqdn.domain.tld> with the Fully Qualified Domain name or IP address of the host to target.

Replace <port-num> with the target TCP port to probe if listening.

The script will respond with ‘YES’ if it’s listening, and ‘NO’ if it’s not.

Leave a comment