Test Connection and Port with PowerShell

16. April 2015

If the Test-Connection is just not enough you can also add a port check to your PowerShell scripts:

$ErrorActionPreference = 'SilentlyContinue' # we do not want to see any errors here

$hostip = "127.0.0.1"
$port = "4441"

Test-Connection $hostip -Count 2 | out-null
    if ([int]$? -eq 0)
    {
    echo "$hostip is offline!"
    }
    else
    {
    echo "$hostip is online!"
    $Socket = New-Object Net.Sockets.TcpClient
    $Socket.Connect($hostip, $port)
    $ErrorActionPreference = 'Continue'
    if ($Socket.Connected)
        {
        echo "-> $port is open!"
        $Socket.Close()
        }
    else
        {
        echo "-> $port is closed or filtered!"
        }
    }
    #resetting the variable between iterations is necessary.
    $Socket = $null

Line 14 to 28 is where the magic happens:

$hostip = "127.0.0.1"
$port = "4441"
$Socket = New-Object Net.Sockets.TcpClient
$Socket.Connect($hostip, $port)
$ErrorActionPreference = 'Continue'
if ($Socket.Connected)
    {
    echo "-> $port is open!"
    $Socket.Close()
    }
else
    {
    echo "-> $port is closed or filtered!"
    }
}
#resetting the variable between iterations is necessary.
$Socket = $null


Result:
127.0.0.1 is online!
-> 4441 is open!

PowerShell Version: 4
Modules: none

#PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *


*