PowerShell Legacy Versions: How to Check Connection of Servers on Certain Ports?

A more updated version is available here.

function Check-NetConnection($server, $port) {
    $session = New-Object System.Net.Sockets.TcpClient;
    $result=$false
    try {
        $session.Connect($server, $port);
        $result=$true;
    } catch {
        $result=$false;
    } finally {
        $session.Close();
       
    }
    return $result;
}
check-netconnection -server 'google.com' -port 443

PowerShell Version 4.0 is required to have access to a function named “Test-NetConnection.” Windows Server 2003, 2008, and 2012 cannot use such cmdlet. This is only available on Windows 8.1 / 2012 R2 and higher. Dread not, here is a work-around:

# Change this variable
$servers=@(
@("kimconnect.com","443"),
@("toyota.com","443"),
@("ajgiarionafonorijiafaerksdajraoe.uga","6532")
);


function Check-NetConnection($server, $port) {
$session = New-Object System.Net.Sockets.TcpClient;
try {
$session.Connect($server, $port);
$true;
} catch {
$false;
} finally {
$session.Close();
}
}

$servers | ForEach {Check-NetConnection "$_[0]" "$_[1]";}

Leave a Reply

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