Home > Net >  Select-string patern match and notmatch
Select-string patern match and notmatch

Time:10-31

I am fairly new to Powershell and have run into a bit of a pickle.

I'm trying to find string "o_dwh" in scripts, but if there is exec before this statement like this - "exec o_dwh" - I don't want to select that. How do I do that?

So far I have this:

Get-ChildItem -Path "$packagepath\Scripts\" -Include *.txt -Recurse | Select-String -Pattern "o_dwh"

I tried this, but I know it's wrong:

Get-ChildItem -Path "$packagepath\Scripts\" -Include *.txt -Recurse | Select-String -Pattern "o_dwh" and "exec o_dwh" -notmatch

CodePudding user response:

I think this should work fine using a negative lookbehind (?<!exec ) to match only those o_dwh preceded by anything but exec , a simple example:

# matches only last 2 lines

@'
something something exec o_dwh
exec o_dwh something
something o_dwh something
o_dwh something something
'@ -split '\r?\n' | Select-String '(?<!exec )o_dwh'

So, assuming this is what you needed, then the code would be (-Filter is preferable here instead of -Include):

Get-ChildItem -Path "$packagepath\Scripts" -Filter *.txt -Recurse |
    Select-String -Pattern '(?<!exec )o_dwh'

See https://regex101.com/r/VupVNA/1 for details.

CodePudding user response:

This also solved my issue, but its not that elegant.

Get-ChildItem -Path "$packagepath\Scripts\" -Include *.txt -Recurse | Select-String -Pattern "o_dwh" | Where-Object line -NotMatch "exec o_dwh"
  • Related