在 windows 中获取本地端口号 7
Get local port numbers in windows 7
我正在尝试获取所有处于 listening 状态的 local ports。使用
netstat -a -n
我得到以下输出:
Proto Local Address Foreign Address State
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING //for example, demo data is given
但我只想获取端口号。
1111 //for ex, this is in listening state.
在Windows10,我可以用
Get-NetTCPConnection -State Listen | group localport -NoElement
有效但此命令在 Windows 7
上不可用
不确定是否有可用的 Windows 7 cmdlet,但您可以解析 netstat 结果:
$objects = netstat -a -n |
select -Skip 4 |
ForEach-Object {
$line = $_ -split ' ' | Where-Object {$_ -ne ''}
if ($line.Count -eq 4)
{
New-Object -TypeName psobject -Property @{
'Protocol'=$line[0]
'LocalAddress'=$line[1]
'ForeignAddress'=$line[2]
'State'=$line[3]}
}
}
然后您可以使用如下方式检索端口:
$objects | Where State -eq LISTENING | Select LocalAddress | Foreach {
$_ -replace '.*:(\d+).*', ''
}
我正在尝试获取所有处于 listening 状态的 local ports。使用
netstat -a -n
我得到以下输出:
Proto Local Address Foreign Address State
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING //for example, demo data is given
但我只想获取端口号。
1111 //for ex, this is in listening state.
在Windows10,我可以用
Get-NetTCPConnection -State Listen | group localport -NoElement
有效但此命令在 Windows 7
上不可用不确定是否有可用的 Windows 7 cmdlet,但您可以解析 netstat 结果:
$objects = netstat -a -n |
select -Skip 4 |
ForEach-Object {
$line = $_ -split ' ' | Where-Object {$_ -ne ''}
if ($line.Count -eq 4)
{
New-Object -TypeName psobject -Property @{
'Protocol'=$line[0]
'LocalAddress'=$line[1]
'ForeignAddress'=$line[2]
'State'=$line[3]}
}
}
然后您可以使用如下方式检索端口:
$objects | Where State -eq LISTENING | Select LocalAddress | Foreach {
$_ -replace '.*:(\d+).*', ''
}