PowerShell实现测试端口可用性脚本分享

利用简单的TCP套接字来简单判断一个端口是否可用:

代码如下:

Function Test-PortAvailable

{

    param(

    [validaterange(1,65535)]

    [int]$Port

    )

    $sockt=New-Object System.Net.Sockets.Socket -ArgumentList 'InterNetwork','Stream','TCP'

    $ip = (Get-NetIPConfiguration).IPv4Address |

        Select -First 1 -ExpandProperty IPAddress

    $ipAddress = [Net.IPAddress]::Parse($ip)

    Try

    {

        $ipEndpoint = New-Object System.Net.IPEndPoint $ipAddress,$port

        $sockt.Bind($ipEndpoint)

        return $true

    }

    Catch [exception]

    {

        return $false

    }

    Finally

    {

        $sockt.Close()

    }

}

使用示例:

代码如下:

PS> Test-PortAvailable -Port 102

True

PS> Test-PortAvailable -Port 1025

False

相关推荐