PoshCode Archive  Artifact [82d0aa94c3]

Artifact 82d0aa94c3e9726a4369ef2cfccbaece91c11be200f59c3f65b37c9d98c5661e:

  • File Test-Port.ps1 — part of check-in [a443f7427f] at 2018-06-10 13:15:50 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: 2791
# x-archived: 2016-07-20T16:05:22
# x-published: 2011-07-14T08:47: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}