PowerShell v5.1 测试网口

ind*_*die 3 powershell

我想在 Windows 7 上使用 PowerShell v5.1 检查端口是否打开。

在装有 PowerShell v5.1 的 Windows 10 笔记本电脑上,我可以使用

Test-NetConnection -ComputerName <IP> -Port <Port>
Run Code Online (Sandbox Code Playgroud)

但是,在我的 Windows 7 笔记本电脑上Test-NetConnection找不到 cmdlet。我可以Test-Connection使用,但该 cmdlet 不允许我指定端口。

有没有办法在 Windows 7 上使用 PowerShell 5.1 测试网络端口是否打开?如何取回Test-NetConnectioncmdlet?

sod*_*low 5

由于System.Net.Sockets.TcpClient当端口未打开时似乎会引发错误,因此我宁愿try/catch在此处使用:

$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"
}
Run Code Online (Sandbox Code Playgroud)