-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTest-TCPPortConnection.ps1
76 lines (63 loc) · 1.86 KB
/
Test-TCPPortConnection.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
##### Test-TCPPortConnection: Test a TCP Port (v1)
function Test-TCPPortConnection {
<#
.SYNOPSIS
Test the response of a computer to a specific TCP port
.DESCRIPTION
Test the response of a computer to a specific TCP port
.PARAMETER ComputerName
Name of the computer to test the response for
.PARAMETER Port
TCP Port number(s) to test
.INPUTS
System.String.
System.Int.
.OUTPUTS
None
.EXAMPLE
PS C:\> Test-TCPPortConnection -ComputerName Server01
.EXAMPLE
PS C:\> Get-Content Servers.txt | Test-TCPPortConnection -Port 22,443
#>
[CmdletBinding()][OutputType('System.Management.Automation.PSObject')]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the computer to test",
ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[Alias('CN','__SERVER','IPAddress','Server')]
[String[]]$ComputerName,
[Parameter(Position=1)]
[ValidateRange(1,65535)]
[Int[]]$Port = 3389
)
begin {
$TCPObject = @()
}
process {
foreach ($Computer in $ComputerName){
foreach ($TCPPort in $Port){
$Connection = New-Object Net.Sockets.TcpClient
try{
$Connection.Connect($Computer,$TCPPort)
if ($Connection.Connected){
$Response = “Open”
$Connection.Close()
}
}
catch [System.Management.Automation.MethodInvocationException]{
$Response = “Closed / Filtered”
}
$Connection = $null
$hash = @{
ComputerName = $Computer
Port = $TCPPort
Response = $Response
}
$Object = New-Object PSObject -Property $hash
$TCPObject += $Object
}
}
}
end {
Write-Output $TCPObject
}
}