如何选择特定列

时间:2011-06-18 12:04:40

标签: powershell

我需要提取特定列的值。我需要解析用cmd:

生成的输出
netstat -an |

Select-String "TCP\s+.+\:.+\s+(.+)\:(\d+)\s+(\w+)" |

ForEach-Object {

    $key = $_.matches[0].Groups[1].value

    $Status = $_.matches[0].Groups[3].value.

打印时超过2个字符串给出了外部IP和连接状态。我需要一个端口号为本地IP的列,外部IP连接到该列。

2 个答案:

答案 0 :(得分:5)

如果您在Windows 8或Windows Server 2012上运行,可以在Powershell V3中使用以下命令示例:

使用Select-Object进行流水线操作

Get-NetTCPConnection | Select LocalAddress,LocalPort,RemoteAddress,RemotePort

单独选择每个属性

(Get-NetTCPConnection).LocalAddress
(Get-NetTCPConnection).LocalPort
(Get-NetTCPConnection).RemoteAddress
(Get-NetTCPConnection).RemoteAddress

使用每个属性创建变量

$LocalAddress = (Get-NetTCPConnection).LocalAddress
$LocalPort = (Get-NetTCPConnection).LocalPort
$Remote Address = (Get-NetTCPConnection).RemoteAddress
$RemotePort = (Get-NetTCPConnection).RemoteAddress

这些都应该作为列表出现。

希望这会有所帮助:)

答案 1 :(得分:2)

我不确定你的意思是什么,但我已经调整了你的正则表达式,这得到了本地和外国地址和端口:

netstat -an |

Select-String "TCP\s+(.+)\:(.+)\s+(.+)\:(\d+)\s+(\w+)" |

ForEach-Object {

    $LocalAddress =  $_.matches[0].Groups[1].value
    $LocalPort =  $_.matches[0].Groups[2].value
    $ForeignAddress = $_.matches[0].Groups[3].value
    $ForeignPort = $_.matches[0].Groups[4].value

    Write-Output "ForeignAddress: $ForeignAddress `t ForeignPort: $ForeignPort `t LocalAddress: $LocalAddress `t LocalPort: $LocalPort"
}