-
Notifications
You must be signed in to change notification settings - Fork 2
/
Test-Port.ps1
77 lines (60 loc) · 1.44 KB
/
Test-Port.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
<#
.SYNOPSIS
Test if a port is listening on a remote computer
.DESCRIPTION
Test if a port is listening on a remote computer
Returns true or false.
.PARAMETER ComputerName
Computername
.PARAMETER IP
IP Address. Optional
.PARAMETER Port
Port number
.PARAMETER Protocol
Protocol
.EXAMPLE
test-port -computername server1 -port 25 -protocol TCP
.NOTES
Daryl Bizsley 2015
#>
function Test-Port
{
Param(
[parameter(ParameterSetName='ComputerName', Position=0)]
[string]
$ComputerName,
[parameter(ParameterSetName='IP', Position=0)]
[System.Net.IPAddress]
$IPAddress,
[parameter(Mandatory=$true , Position=1)]
[int]
$Port,
[parameter(Mandatory=$true, Position=2)]
[ValidateSet("TCP", "UDP")]
[string]
$Protocol
)
$RemoteServer = If ([string]::IsNullOrEmpty($ComputerName)) {$IPAddress} Else {$ComputerName};
If ($Protocol -eq 'TCP')
{
$test = New-Object System.Net.Sockets.TcpClient;
Try
{
#Write-Host "Connecting to "$RemoteServer":"$Port" (TCP)..";
$test.Connect($RemoteServer, $Port);
Write-Output $True;
}
Catch
{
Write-Output $False;
}
Finally
{
$test.Dispose();
}
}
If ($Protocol -eq 'UDP')
{
Write-Host "UDP port test functionality currently not available."
}
}