S
S
Seeker2021-05-12 12:50:01
PowerShell
Seeker, 2021-05-12 12:50:01

How to use PowerShell Select-String to filter output based on multiple conditions?

After all, PowerShell has Select-String, an analogue of grep from linux, but I can’t figure out its syntax in any way, how to use several conditions in it.
So I need to see what network connections are open with the "NETSTAT -ano -p TCP" command, but at the same time display only lines that include "ESTABLISHED" and exclude lines with "127.0.0.1:1433" and "10.10.10.5:80"

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Bezrukov, 2021-05-12
@NortheR73

You can make multiple calls to Select-String in succession:

NETSTAT -ano -p TCP | Select-String 'established' | Select-String -NotMatch '127.0.0.1:1433','10.10.10.5:80'

S
Somewhere Intech, 2021-05-12
@john36allTa

using regex:

NETSTAT -ano -p TCP  | Select-String -pattern '^(?!.*?127\.0\.0\.1:1433\s|.*?10\.10\.10\.5:80\s).*ESTABLISHED'

T
Therapyx, 2021-05-12
@Therapyx

You can write the information from this command first into a regular Array string,
$Info = NETSTAT -ano -p TCP
then convert it into a powershell object

$Info = $Info [3..$Info.count] | ConvertFrom-String | select p2,p3,p4,p5

after which you can already very conveniently manipulate the data as you want it. For example
$result = $Info  | Where-Object {$_.P5 -eq "ESTABLISHED" -and $_.P4 -eq "127.0.0.1:1433"}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question