Port scanning in PowerShell

The below script in PowerShell can scan a given range of ports for a specific server and will – if a port on the server is open – return the text: TCP port <PORT NUMBER) is open!

foreach ($port in <START PORT>..<END PORT>) {If (($a=Test-NetConnection <SERVER> -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open!"}}

Example

foreach ($port in 3388..3390) {If (($a=Test-NetConnection MYSERVER -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open!"}}

TCP port 3389 is open!

If you only want to scan for one port, you can use the following syntax

Test-NetConnection <SERVER> -port <PORT>

or

TNC <SERVER> -port <PORT>