Posted On July 28, 2021

PowerShell: Initiate Tests on Certain Ports

kimconnect 0 comments
blog.KimConnect.com >> Codes , Networking >> PowerShell: Initiate Tests on Certain Ports

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)

Leave a Reply

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

Related Post

PowerShell: Installing or Including an Application On a Computer or Scripting Session

Sample Usage: PS C:\WINDOWS\system32> includeapp -appName notepadplusplus -appExe notepad++notepadplusplus version 7.91.0.0 already exists.True function includeApp($appName,$appExe=$False,$version){…

Install FOG, an Open Source Machine Backup and Cloning Solution

- Install Ubuntu or Centos - Install FOG - On Windows Client, run sysprep, then…

CCIE Exam Day Overview

1. Network Principles 2. Layer 2 Technologies: LAN switching & WAN Circuits, layer 2 multicast…