批量测试服务器网络端口脚本

#PS C:\Users\admin.MYAD\Desktop> .\test.ps1 -Dir C:\Users\admin.MYAD\Desktop\test.txt -Port 443

param($Dir,$Port)

function Test-PortAlive {
[CmdletBinding()]
[OutputType([System.boolean])]
param(
[Parameter(ValueFromPipeline=$true)][System.String[]]$server,
[int]$port
)

$socket = new-object Net.Sockets.TcpClient
$connect = $socket.BeginConnect($server, $port, $null, $null)
$NoTimeOut = $connect.AsyncWaitHandle.WaitOne(500, $false)

if ($NoTimeOut) {
    $socket.EndConnect($connect) | Out-Null
    return $true               
}
else {
    return $false
}

}

$DesktopPath=[Environment]::GetFolderPath("Desktop")+"\"
#echo $DesktopPath

$today=Get-Date
$LogFile=$DesktopPath+($today.ToString('yyyy-MM-dd'))+".txt"
#echo $LogFile

$TxtCon=Get-Content($Dir)

foreach($LineCon in $TxtCon)
{

if(Test-PortAlive -port $Port $LineCon)
{
echo ("TCP Connect "+$LineCon+":"+$Port+" successful") | Out-File -Append $LogFile
}
else
{
echo ("TCP Connect "+$LineCon+":"+$Port+" fail") | Out-File -Append $LogFile
}

}

猜你喜欢

转载自blog.51cto.com/642364/2380446