I\'m using NETSTAT command in PowerShell. I need to grab the list of foreign addresses which starts with XYZ name and are ESTABLISHED as state using TCP connections.
<+1
for @E.V.I.L. answer but it chokes the (slow) stream from NetStat
due to the assignments ($netstats
and $final
).
To keep the pipeline streaming, it is better to avoid assignments, like:
netstat -p TCP -f | Select -Skip 4 | ForEach {
$Properties = $_.Trim() -split '[\s]+'
[PSCustomObject]@{
'Proto'= $Properties[0]
'Local Address'= $Properties[1]
'Foreign Address'= $Properties[2]
'State'= $Properties[3]
}
}
By adding e.g. | Select -Expand 'Foreign Address'
, you just get the Foreign Address
.
Running netstat /? yields, among other things:
-f Displays Fully Qualified Domain Names (FQDN) for foreign addresses.
Parse, using New-PSObjectFromMatches:
netstat -f |
new-psobjectfrommatches -pattern "(TCP|UDP)\s+(\S+)\s+(\S+):(\S+)\s+(\S+)" -property $nul,TCP/UDP,LocalAddress,ForeignAddress,Protocol,State |
where {(
($_.TCP/UDP -eq 'TCP') -and
($_.State -eq 'ESTABLISHED') -and
($_.ForeignAddress -like 'XYZ*')
)} | select -ExpandProperty ForeignAddress
$netstats = netstat -p TCP -f
$data = $netstats[4..($netstats.count)] #The good info starts on index 4
foreach($line in $data){
$line = $line -split ' ' | ? {$_ -ne ''}
$final += @(New-Object -TypeName psobject -Property @{'Proto'=$line[0];'LAddress'=$line[1];'FAddress'=$line[2];'State'=$line[3]})
}
$netstat_results = $final
$netstat_results | ? {$_.state -eq 'ESTABLISHED'}
Now it should be easy getting the data you want after parsing the text that netstat returns.