Search code examples
windowspowershellwindows-7powershell-5.0

Get local port numbers in windows 7


I am trying to get all local ports that are in listening state. Using

netstat -a -n

I get the following output:

Proto  Local Address          Foreign Address        State
TCP    0.0.0.0:8080             0.0.0.0:0              LISTENING //for example, demo data is given

But I only wan't to get the port numbers.

1111 //for ex, this is in listening state.

In Windows 10, I can use

Get-NetTCPConnection -State Listen | group localport -NoElement

Which works but this command isn't available on Windows 7


Solution

  • Not sure whether there is a Windows 7 cmdlet available but you could parse the netstat result:

    $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]}
            }
        }
    

    Then you can retrieve the ports using something like this:

    $objects | Where State -eq LISTENING | Select LocalAddress | Foreach { 
        $_ -replace '.*:(\d+).*', '$1' 
    }