This appears to be a duplicate of another post.

function initTestPort($portNumber=5985,$maxTests=3){

  function getIndexDifference {
    param(
      [String] $string1,
      [String] $string2
    )
    if ( $string1 -ceq $string2 ) {
      return -1
    }
    for ( $i = 0; $i -lt $string1.Length; $i++ ) {
      if ( $string1[$i] -cne $string2[$i] ) {
        return $i
      }
    }
    return $string1.Length
  }  

  $baseLine=(netstat -ano -p tcp|select-string "$portNumber"|out-string).trim()
  if(!$baseline){
      write-warning "$env:computername doesn't have any service listening on port $portNumber"
      exit
  }else{
      write-host "$env:computername is now listening on port $portNumber"
      do{
          $status=(netstat -ano -p tcp|select-string "$portNumber"|out-string).trim()
          if($status -ne $baseline){
            $maxTests--  
            $matchIndex=getIndexDifference $status $baseline
            $difference=$status.Substring($matchIndex).Trim()
            write-host "$maxTests remaining => $difference"
            $status=$baseline
            $null=ping 127.0.0.1 -n 1
          }
      }until(!$maxTests)
  }
}
# Test reachability from a client machine
$server='nameOrIpHere'
$port=5985
(new-object Net.Sockets.TcpClient).Connect($server, $port)