Search code examples
powershellbooleanmatchselect-string

Return True if two patterns are found in text with Powershell


This seems like a simple task but I can't seem to get it to work. I want to be able to read a text file and if two exact patterns are found return True. If it only finds one then it returns false.

I tried this, but it is not working:

Get-Content $log_path | Select-String -pattern "\bInstallation of\b|\bfailed\b" -AllMatches -quiet

What can I try next?


Solution

  • Your pattern contained a or | statement which basically says.

    If one or the other (Installation or failed) is present, then it's a match. What you want is to use a wildcard instead so both word and the in-between are part of the same match.

    Select-String -pattern "\bInstallation .* failed\b"  -quiet
    

    Additional Notes

    When having issues, there are online regex tester to allow you to test your regular expression.

    I personally like a lot RegexHero even though you need IE because it is done in Silverlight because it has an Analyze section for your regular expression which breaks down your expression and gives an explanation in words of what you are doing.

    Super useful when learning or just when dealing with always more complex epxressions.

    For instance, your initial regular expression. Initial expression

    Although I did not personally used it, RegexStorm also looks promising and is not IE restricted.