Pedro Sales Pedro Sales - 3 months ago 24
PowerShell Question

exclude search pattern with select-string in powershell

I'm using select string to search a file for errors. Is it possible to exclude search patterns as with grep. Ex:

grep ERR* | grep -v "ERR-10"

select-string -path logerror.txt -pattern "ERR"


logerror.txt

OK
ERR-10
OK
OK
ERR-20
OK
OK
ERR-10
ERR-00


I want to get all the ERR lines, but not the ERR-00 and ERR-10

Answer

I guess you can use Where-Object here.

Write-Output @"
OK
ERR-10
OK
OK
ERR-20
OK
OK
ERR-10
ERR-00
"@ > "C:\temp\log.txt"

# Option 1.
Get-Content "C:\temp\log.txt" | Where-Object { $_ -Match "ERR*"} | Where-Object { $_ -NotMatch "ERR-[01]0"}

# Option 2.
Get-Content "C:\temp\log.txt" | Where-Object { $_ -Match "ERR*" -and $_ -NotMatch "ERR-[01]0"}
Comments