-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathGet-TCPResponse.ps1
102 lines (91 loc) · 3.5 KB
/
Get-TCPResponse.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Function Get-TCPResponse {
<#
.SYNOPSIS
Tests TCP port of remote or local system and returns a response header
if applicable
.DESCRIPTION
Tests TCP port of remote or local system and returns a response header
if applicable
If server has no default response, then Response property will be NULL
.PARAMETER Computername
Local or remote system to test connection
.PARAMETER Port
TCP Port to connect to
.PARAMETER TCPTimeout
Time until connection should abort
.NOTES
Name: Get-TCPResponse
Author: Boe Prox
Version History:
1.0 -- 15 Jan 2014
-Initial build
.INPUTS
System.String
.OUTPUTS
Net.TCPResponse
.EXAMPLE
Get-TCPResponse -Computername Exchange1 -Port 25
Computername : Exchange1
Port : 25
IsOpen : True
Response : 220 SMTP Server Ready
Description
-----------
Checks port 25 of an exchange server and displays header response.
#>
[OutputType('Net.TCPResponse')]
[cmdletbinding()]
Param (
[parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
[Alias('__Server','IPAddress','IP')]
[string[]]$Computername = $env:Computername,
[int[]]$Port = 902,
[int]$TCPTimeout = 1000
)
Process {
ForEach ($Computer in $Computername) {
ForEach ($_port in $Port) {
$stringBuilder = New-Object Text.StringBuilder
$tcpClient = New-Object System.Net.Sockets.TCPClient
$connect = $tcpClient.BeginConnect($Computer,$_port,$null,$null)
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
If (-NOT $wait) {
$object = [pscustomobject] @{
Computername = $Computer
Port = $_Port
IsOpen = $False
Response = $Null
}
} Else {
While ($True) {
#Let buffer
Start-Sleep -Milliseconds 1000
Write-Verbose "Bytes available: $($tcpClient.Available)"
If ([int64]$tcpClient.Available -gt 0) {
$stream = $TcpClient.GetStream()
$bindResponseBuffer = New-Object Byte[] -ArgumentList $tcpClient.Available
[Int]$response = $stream.Read($bindResponseBuffer, 0, $bindResponseBuffer.count)
$Null = $stringBuilder.Append(($bindResponseBuffer | ForEach {[char][int]$_}) -join '')
} Else {
Break
}
}
$object = [pscustomobject] @{
Computername = $Computer
Port = $_Port
IsOpen = $True
Response = $stringBuilder.Tostring()
}
}
$object.pstypenames.insert(0,'Net.TCPResponse')
Write-Output $object
If ($Stream) {
$stream.Close()
$stream.Dispose()
}
$tcpClient.Close()
$tcpClient.Dispose()
}
}
}
}