PoshCode Archive  Artifact [65263fdb45]

Artifact 65263fdb45bc9a963ed21ef8432c91fdf41a63abf1322d958133ba696c2c99b5:

  • File Test-Port.ps1 — part of check-in [3ee247e3b5] at 2018-06-10 13:28:58 on branch trunk — Test-Port creates a TCP connection to specified port. By default it connects to port 135 with a timeout of 3secs. (user: BSonPosh size: 1334)

# encoding: ascii
# api: powershell
# title: Test-Port.ps1
# description: Test-Port creates a TCP connection to specified port. By default it connects to port 135 with a timeout of 3secs.
# version: 0.1
# author: BSonPosh
# license: CC0
# x-poshcode-id: 3665
# x-archived: 2016-07-20T16:02:51
# x-published: 2013-09-27T06:29:00
#
#
Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)
 
# Test-Port.ps1
# Does a TCP connection on specified port (135 by default)
 
$ErrorActionPreference = "SilentlyContinue"
 
# Create TCP Client
$tcpclient = new-Object system.Net.Sockets.TcpClient
 
# Tell TCP Client to connect to machine on Port
$iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
 
# Set the wait time
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
 
# Check to see if the connection is done
if(!$wait)
{
    # Close the connection and report timeout
    $tcpclient.Close()
    if($verbose){Write-Host "Connection Timeout"}
    Return $false
}
else
{
    # Close the connection and report the error if there is one
    $error.Clear()
    $tcpclient.EndConnect($iar) | out-Null
    if(!$?){if($verbose){write-host $error[0]};$failed = $true}
    $tcpclient.Close()
}
 
# Return $true if connection Establish else $False
if($failed){return $false}else{return $true}