Powershell检测端口状态 2


你可以通过端口来访问远程电脑,下面有个函数Test-Port,用它可以测试一个远程电脑或IP的任意端口。
下例默认是使用的是Powershell的5985端口,延迟为1秒:

#requires -Version 1
function Test-Port
{
    Param([string]$ComputerName,$port = 5985,$timeout = 1000) 
    try
    {
        $tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
        $iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
        $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
        if(!$wait)
        {
            $tcpclient.Close()
            return $false
        }
        else
        {
            # Close the connection and report the error if there is one
            
            $null = $tcpclient.EndConnect($iar)
            $tcpclient.Close()
            return $true
        }
    }
    catch 
    {
        $false 
    }
}

下面你还可以测试一台电脑是否开启了Powershell远程:

 
PS> Test-Port -ComputerName TestServer 
False

默认是1秒的延迟,稍后即可查看结果。
原文地址:Testing a Network Port

本文链接: https://www.pstips.net/testing-a-network-port.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

回复 codecook 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

2 条评论 “Powershell检测端口状态