This situation is similar to those presented in The Greatest Regex Trick Ever --- a great read for anyone learning regex. Whie the negative lookahead posted by Glorfindel works well in this case, this technique is easily expandable to multiple exclusions, lookbehinds combined with lookaheads, etc. and still remain readable.
The essence of the trick is to capture all exclusions in the overall match and the desired content in Group 1. For the OP, the regex would look like:
'ERROR: Opening local file|(ERROR:.+$)'
Sample:
(In working code, <Here-string> -Split "`n"
would be replaced by:
Get-Contnet 'c:\Path\To\Error.log'
)
@'
ERROR: Another error
ERROR: Writing local file (I want to be alerted to this)
ERROR: Opening local file (I don't want to be alerted to this)
THIS is not an error
'@ -Split "`n" | ForEach {
$_ -match 'ERROR: Opening local file|(ERROR:.+$)' | out-null
$matches[1]
}
Screen Capture:
PS C:\> @'
>> ERROR: Another error
>> ERROR: Writing local file (I want to be alerted to this)
>> ERROR: Opening local file (I don't want to be alerted to this)
>> THIS is not an error
>> '@ -Split "`n" | ForEach {
>> $_ -match 'ERROR: Opening local file|(ERROR:.+$)' | out-null
>> $matches[1]
>> }
ERROR: Another error
ERROR: Writing local file (I want to be alerted to this)
PS C:\>
Again, the beauty of this technique is it's easily expandable:
'Exception1|Exception2|Exception3|(Desired Match)'
error:
, and then filter for NOT: opening
. – Lee_Dailey Aug 25 '20 at 15:03^ERROR: [^O]
. – Dai Aug 25 '20 at 23:55