Share via


Testing a Port

Load blancers are great, but we don't get iAdmin access to them, so the only way we know if a host is down is to visually scan the web UI.  And for whichever EIEIO security standard, we have two-factor auth which times out after a very aggressive interval, etc.  Long story aside, I find myself needing to sanity-check our lab's load balancer.

Rules that test for a given send/response handshake to a given URL is easy: System.Net.WebClient.  Ones that talk to our product-specific ports are a little trickier.  We need to see if we can

function Test-Port {
 param (
  [string[]]$computer = @(),
  [string]$port = 3389 # RDP port
 );
 
 function Return-Status {
  param ($status = $false);
   $status| Select-Object -Property @{
    name = 'name'; expression = { $myComputer; }
   }, @{
    name = 'port'; expression = { $port; }
   }, @{
    name = 'status'; expression = { [bool]$status; }
   }
 }
 foreach ($myComputer in $computer) {
  Write-Verbose "Processing $myComputer";
  
  $pingStatus = $null;
  & {
   trap { continue; }
   (New-Object System.Net.NetworkInformation.Ping).Send($myComputer,1).Status | Set-Variable -Scope 1 -Name pingStatus;
  }
  
  if ($pingStatus -ne 'Success') {
   Write-Warning "Unable to ping $myComputer";
   & Return-Status $false;
   continue;
  } else {
   Write-Verbose "$myComputer is pingable";
  }
  if ($socket = New-Object System.Net.Sockets.TcpClient($myComputer, $port)) {
   & Return-Status $true;
  } else {
   Write-Warning "Unable to connect to $myComputer on port $port";
   & Return-Status $false; 
  }
 }
}