powershellwindows-10powershell-v5.1

Selecting multiple strings from the output of command in powershell


This may be a simple question that has been answered before but I just couldn't find it. I am trying to filter out unneeded text/output from a simple script I made.

$stop = 2
do {
clear
netstat -a -n -o | Select-String "ESTABLISHED"
Start-Sleep -Seconds 5
} while ($stop -ne 1)

I want to add more than just established connections to the output window such as both the UDP and TCP connections but remove the loopback addresses. If there is a better way or more efficient way of doing this that would be great.


Solution

  • Since you're on Windows 10, you have access to the Get-NetTCPConnection cmdlet. Instead of parsing netstat output, you can work with objects:

    Get-NetTCPConnection |
        Where-Object RemoteAddress -notin '127.0.0.1','0.0.0.0', '::'
    

    For UDP:

    Get-NetUDPEndpoint