When you don’t have the test-connection PowerShell cmdlet (if I’m not mistaken, this is not present in P.S. 2.0), you can use the function below to achieve similar results:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
function Test-Port($hostname, $port) { # This works no matter in which form we get $host - hostname or ip address try { $ip = [System.Net.Dns]::GetHostAddresses($hostname) | select-object IPAddressToString -expandproperty IPAddressToString if($ip.GetType().Name -eq "Object[]") { #If we have several ip's for that address, let's take first one $ip = $ip[0] } } catch { Write-Host "Possibly $hostname is wrong hostname or IP" return } $t = New-Object Net.Sockets.TcpClient # We use Try\Catch to remove exception info from console if we can't connect try { $t.Connect($ip,$port) } catch {} if($t.Connected) { $t.Close() $object = [pscustomobject] @{ Hostname = $hostname IP = $IP TCPPort = $port GetResponse = $True } Write-Output $object } else { $object = [pscustomobject] @{ Computername = $IP TCPPort = $port GetResponse = $False } Write-Output $object } Write-Host $msg } |
