Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
check if certain ports can be reached from your internal network or if they are blocked
# check if certain ports can be reached from your internal network or if they are blocked
# note: adapted from https://github.com/JustinGrote/Scripts/blob/master/Test-TCPPort.ps1
function Test-Port()
{
Param([string]$srv, $port = 135, $timeoutMs = 3000, [switch]$verbose)
$failed = $false
$ErrorActionPreference = "SilentlyContinue"
$tcpclient = New-Object System.Net.Sockets.TcpClient
$asyncRes = $tcpclient.BeginConnect($srv,$port,$null,$null)
# wait for the specified number of milliseconds
$wait = $asyncRes.AsyncWaitHandle.WaitOne($timeoutMs, $false)
# check for timeout
if(!$wait)
{
# close the connection and report timeout
$tcpclient.Close()
if ($verbose)
{
Write-Host "Connection Timeout"
}
$failed = $true
}
else
{
# close the connection and report the error if there is one
$Error.Clear()
$tcpclient.EndConnect($asyncRes) | Out-Null
if(!$?)
{
if($verbose)
{
Write-Host $Error[0]
}
$failed = $true
}
$tcpclient.Close()
}
return !$failed
}
$openPorts = @()
$mailPorts = 25,110,465,587,995
foreach ($port in $mailPorts)
{
$result = Test-Port portquiz.net -port $port -timeoutMs 500
if ($result)
{
Write-Host "Port is open: $port" -ForegroundColor Green
$openPorts += $port
} else {
Write-Host "Port is closed: $port" -ForegroundColor Red
}
}
Write-Host "Detected open ports:"
$openPorts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment