PoshCode Archive  Artifact [af426ed8e5]

Artifact af426ed8e50a2063cb26cc435194fc92cc051169f248a1a1652072750357bad4:

  • File Test-Port.ps1 — part of check-in [c31e7f5216] at 2018-06-10 14:25:08 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: 1332)

# 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: 85
# x-archived: 2017-05-22T04:58:58
# x-published: 2008-12-31T14:18: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}