PowerShell实现测试端口可用性脚本分享
利用简单的TCP套接字来简单判断一个端口是否可用:
FunctionTest-PortAvailable
{
param(
[validaterange(1,65535)]
[int]$Port
)
$sockt=New-ObjectSystem.Net.Sockets.Socket-ArgumentList'InterNetwork','Stream','TCP'
$ip=(Get-NetIPConfiguration).IPv4Address|
Select-First1-ExpandPropertyIPAddress
$ipAddress=[Net.IPAddress]::Parse($ip)
Try
{
$ipEndpoint=New-ObjectSystem.Net.IPEndPoint$ipAddress,$port
$sockt.Bind($ipEndpoint)
return$true
}
Catch[exception]
{
return$false
}
Finally
{
$sockt.Close()
}
}
使用示例:
PS>Test-PortAvailable-Port102 True PS>Test-PortAvailable-Port1025 False