-
Notifications
You must be signed in to change notification settings - Fork 1
/
Test-PortConnection.ps1
58 lines (51 loc) · 1.46 KB
/
Test-PortConnection.ps1
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function Test-PortConnection {
param(
[String]$ComputerName="localhost",
[Int16]$Port=8080
,[ValidateSet('TCP','UDP')]
[string]$Type='TCP'
)
$Status = [PSCustomObject]@{
'ComputerName' = $Computername
'Port' = $Port
'Type' = $Type
'Open' = $Null
}
switch ($Type) {
'UDP' { $socket = new-object System.Net.Sockets.UdpClient }
Default { $socket = new-object System.Net.Sockets.TcpClient }
}
try {
$socket.Connect($ComputerName, $port)
} catch [System.Net.Sockets.SocketException] {
if($PSItem.Exception -match "actively refused"){
$Status.Open = $false
}
if($PSItem.Exception -match "No such host is known"){
Write-Warning "No Host: $ComputerName"
}
} catch {
Throw $PSItem
}
if($Type -eq 'UDP'){
UDPTestData($socket)
}
if ($socket.Connected) {
$Status.Open = $True
}
$socket.Close()
$socket.Dispose()
Write-Output $Status
}
function UDPTestData($Socket){
$Enc = New-Object System.Text.ASCIIEncoding
$byte = $Enc.GetBytes('teststring')
$socket.Client.ReceiveTimeout = 200
$socket.Send($byte, $byte.length) > $null #Do not return data length
$Endpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any, 0)
try {
$Recieve = $socket.Receive([ref]$Endpoint)
} catch {
return $psitem
}
}