PowerShell 技能连载 - 扫描端口

以下是一个扫描本地或远程系统端口的一个直接的方法。您甚至可以指定一个超时值(以毫秒为单位):

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
function Get-PortInfo
{
param
(
[Parameter(Mandatory)]
[Int]
$Port,

[Parameter(Mandatory)]
[Int]
$TimeoutMilliseconds,

[String]
$ComputerName = $env:COMPUTERNAME
)

# try and establish a connection to port async
$tcpobject = New-Object System.Net.Sockets.TcpClient
$connect = $tcpobject.BeginConnect($computername,$port,$null,$null)

# wait for the connection no longer than $timeoutMilliseconds
$wait = $connect.AsyncWaitHandle.WaitOne($timeoutMilliseconds,$false)

# return rich information
$result = @{
ComputerName = $ComputerName
}

if(!$wait) {
# timeout
$tcpobject.Close()
$result.Online = $false
$result.Error = 'Timeout'
} else {
try {
# try and complete the connection
$null = $tcpobject.EndConnect($connect)
$result.Online = $true
}
catch {
$result.Online = $false
}
$tcpobject.Close()
}
$tcpobject.Dispose()

[PSCustomObject]$result
}

扫描端口现在变得十分简单:

1
2
3
4
5
6
7
8
9
10
11
12
PS> Get-PortInfo -Port 139 -TimeoutMilliseconds 1000

ComputerName Online
------------ ------
DESKTOP-7AAMJLF True


PS> Get-PortInfo -Port 139 -TimeoutMilliseconds 1000 -ComputerName storage2

Error ComputerName Online
----- ------------ ------
Timeout storage2 False
评论