The plan
Option 1
$hostname = 'HOSTNAME'
$port = '104'
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
}
Test-Port $hostname $port
Option 2
# Validate connection state of hosts in the environment.
$AdComputers = (Get-ADComputer -Filter *).Name
ForEach($TargetHost in $AdComputers)
{
# Test from localhost to remote AD hosts
Test-Connection -ComputerName $TargetHost -Count 1
# Use current host valiadate remote hosts
Invoke-Command -ComputerName $TargetHost -ScriptBlock {
ForEach ($TargetHost in $Using:AdComputers)
{Test-Connection -ComputerName $TargetHost -Count 1}
}
}
Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
DC01 EX01 192.168... 32 0
...
EX01 DC01 192.168... 32 0
...
# If you want the port inclusion, then something like this.
$AdComputers = (Get-ADComputer -Filter *).Name
ForEach($TargetHost in $AdComputers)
{
# Test from localhost to remote AD hosts
"Local processing from source $env:COMPUTERNAME"
Test-NetConnection -ComputerName $TargetHost -Port 445 | Format-Table -AutoSize
# Use current host valiadate remote hosts
Invoke-Command -ComputerName $TargetHost -ScriptBlock {
ForEach ($TargetHost in $Using:AdComputers)
{
"Remote processing from source $env:COMPUTERNAME"
Test-NetConnection -ComputerName $TargetHost -Port 445 | Format-Table -AutoSize
}
}
}