Domanda

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.

I stuck up at parsing because of the NETSTAT result as below.

PS C:\Windows\system32> .\NETSTAT.EXE

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    10.125.4.233:2310      157.05.39.133:2492     ESTABLISHED

I need the foreign address names not the remote address on the local host only.
Remote address doesn't show the FQDN.

È stato utile?

Soluzione

 $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.

Altri suggerimenti

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 

+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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top