Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell v5.1 test network port

Tags:

powershell

I want to check to see if a port is open using PowerShell v5.1 on Windows 7.

On my Windows 10 laptop with PowerShell v5.1 I can use

Test-NetConnection -ComputerName <IP> -Port <Port>

However, on my Windows 7 laptop the Test-NetConnection cmdlet is not found. I have Test-Connection available, but that cmdlet doesn't allow me to specify a port.

Is there a way on Windows 7 with PowerShell 5.1 to test if a network port is open? How can I get the Test-NetConnection cmdlet back?

like image 373
indyodie Avatar asked May 22 '26 00:05

indyodie


1 Answers

Since System.Net.Sockets.TcpClient seems to throw an error when port is not open, I'd rather use a try/catch here:

$ip = "127.0.0.1"
$port = "80"

try {
    $socket = New-Object System.Net.Sockets.TcpClient($ip, $port)

    if($socket.Connected) {
        "success"
        $socket.Close()
    }
} catch {
    "error"
}
like image 145
sodawillow Avatar answered May 27 '26 03:05

sodawillow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!