Test-Port (kinda like portqry without verbose output)
We had a little dicussion on www.powershelllive.com forums about the most efficient way to Test a machine before trying a WMI query against it (as it has a log timeout.) My first suggestion was to use a ping (WMI style) but Jeff from http://blog.sapien.com brought up a valid point… what if ICMP is NOT Allowed…
Enter Test-Port. This nifty little script uses the TCPClient Class to test connectivity. Stay tuned as I am planning some mods.
Test-Port
- Takes parameter $srv for Server Name
- Takes Parameter for Port, Defaults to 135 for RPC mapper.
- Takes Timeout.. defaults to 3000 (miliseconds)
- If it cannot connect within timeout… Returns $false
- If it gets exception connecting to port… Returns $false
- If it connects… Returns $True
Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)
$ErrorActionPreference = "SilentlyContinue"
$tcpclient = new-Object system.Net.Sockets.TcpClient
$iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
if(!$wait)
{
$tcpclient.Close()
if($verbose){Write-Host "Connection Timeout"}
Return $false
}
else
{
$error.Clear()
$tcpclient.EndConnect($iar) | out-Null
if($error[0]){if($verbose){write-host $error[0]};$failed = $true}
$tcpclient.Close()
}
if($failed){return $false}else{return $true}
}
tshell :: Sep.18.2007 :: .NET, HowTo, Powershell, Scripting :: No Comments »

This is the VERB police: Pull Over.
Sir, do you realize that “Test” is the officially recognized verb for checking things? Yeah, that’s what I thought. Consider this a warning.
Have a nice day.
[...] As you might guess what we need is a pipeline from Get-QADComputer to Move-QADObject with some kind of where -not pingable in between. Luckily thanks to our fellow MVP Brandon we have the script doing the ping. [...]
[...] PPS: Скрипт test-port можно взять тут, для админов - must have. Posted by xaegr Filed in PowerShell [...]
Maybe this is an silly question. How do you call this function ?
Test-Port(IP) ?
I used Test-Port because Test is an Approved Verb and Port is what I am testing
more Info Here
http://msdn2.microsoft.com/en-us/library/ms714428(VS.85).aspx
That is not my question. My question was how you can put the IP in the script by function name ( parameters)?
But i change the line.. Param([string]$srv=’64.233.167.99′,$port=80,$timeout=3000,[switch]$verbose)
And it seams to work. when i call test-port.
But if you use it like an function… test-port( ….. ) …. = what parameters do you need to enter? I tested with test-port(’64.233.167.99′) in the ps1 file that has the function… and with is not working…
Perhaps I still do not understand your question.
to use this . source the ps1 file and then just call the function.
. c:\scripts\test-port.ps1
test-port “64.233.167.99″
Another option is to remove the function{ and ending }