PoshCode Logo PowerShell Code Repository

Test-Port.ps1 by teste 8 days ago (modification of post by BSonPosh view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/6799"></script>download | new post

Test-Port creates a TCP connection to specified port. By default it connects to port 135 with a timeout of 3secs.

  1. Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)
  2.  
  3. # Test-Port.ps1
  4. # Does a TCP connection on specified port (135 by default)
  5.  
  6. $ErrorActionPreference = "SilentlyContinue"
  7.  
  8. # Create TCP Client
  9. $tcpclient = new-Object system.Net.Sockets.TcpClient
  10.  
  11. # Tell TCP Client to connect to machine on Port
  12. $iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
  13.  
  14. # Set the wait time
  15. $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
  16.  
  17. # Check to see if the connection is done
  18. if(!$wait)
  19. {
  20.     # Close the connection and report timeout
  21.     $tcpclient.Close()
  22.     if($verbose){Write-Host "Connection Timeout"}
  23.     Return $false
  24. }
  25. else
  26. {
  27.     # Close the connection and report the error if there is one
  28.     $error.Clear()
  29.     $tcpclient.EndConnect($iar) | out-Null
  30.     if(!$?){if($verbose){write-host $error[0]};$failed = $true}
  31.     $tcpclient.Close()
  32. }
  33.  
  34. # Return $true if connection Establish else $False
  35. if($failed){return $false}else{return $true}

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me