Created
November 15, 2017 11:58
-
-
Save royharoush/32bb8aa75fd7e7074f1d9f87df2e07c4 to your computer and use it in GitHub Desktop.
a quick script to test for open ports, use by importing the module then calling with ip and port
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Test-Port($hostname, $port) | |
{ | |
# This works no matter in which form we get $host - hostname or ip address | |
try { | |
$ip = [System.Net.Dns]::GetHostAddresses($hostname) | | |
select-object IPAddressToString -expandproperty IPAddressToString | |
if($ip.GetType().Name -eq "Object[]") | |
{ | |
#If we have several ip's for that address, let's take first one | |
$ip = $ip[0] | |
} | |
} catch { | |
Write-Host "Possibly $hostname is wrong hostname or IP" | |
return | |
} | |
$t = New-Object Net.Sockets.TcpClient | |
# We use Try\Catch to remove exception info from console if we can't connect | |
try | |
{ | |
$t.Connect($ip,$port) | |
} catch {} | |
if($t.Connected) | |
{ | |
$t.Close() | |
$msg = "Port $port is operational" | |
} | |
else | |
{ | |
$msg = "Port $port on $ip is closed, " | |
$msg += "You may need to contact your IT team to open it. " | |
} | |
Write-Host $msg | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment