开发者

How to select a specific column

I need to extract values of specific column. I need to parse output generated with 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.

Above 2 strings when printed gives me Foreign IP and connection state. I need a column with port no of local IP to wh开发者_StackOverflowich a foreign IP is connected.


If you are running on Windows 8 or Windows Server 2012, you can use the following command examples in Powershell V3:

Pipelining with Select-Object

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

Selecting each property individually

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

Creating variables using each property

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

These should all come out as lists.

Hope this helps :)


I'm not sure what you mean by a column but I've tweaked your regex and this gets the local and foreign addresses and ports:

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"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜