PoshCode Archive  Artifact Content

Artifact 74cb7e1ef301f23b07c3de84919f1810454d3a0bc1d03272f8b6bd66c323f7aa:

  • File Test-Port.ps1 — part of check-in [512e697590] at 2018-06-10 12:56:39 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: 1298)

# 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: 1208
# x-archived: 2009-07-22T11:40:36
#
#
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}