Reputation: 147
I am currently having an issue with finding multiple conditions within powershell. I am querying a text file, and am looking for a specific name, as well as a specific variable. I am also trying to work from a top down approach via the text file.
The text file looks something like this:
Name1:
Nonsense
VariableA
VariableB
Nonsense
VariableC ==
Name2:
VariableA
Nonsense
VariableB ==
VariableC
I am trying to run a query to first find Name2, and then find the next line that contains both "Variable" and the "==" operator. However, I have no idea where to start with these conditions. If anyone could point me in the right direction I would appreciate it.
Thanks!
Upvotes: 0
Views: 440
Reputation: 200293
Something like this should work:
PS C:\> $txt = Get-Content 'C:\path\to\your.txt' | Out-String
PS C:\> $txt
Name1:
Nonsense
VariableA
VariableB
Nonsense
VariableC ==
Name2:
VariableA
Nonsense
VariableB ==
VariableC
PS C:\> $txt -match 'Name2[\s\S]*?(Variable.*?==)'
True
PS C:\> $matches[1]
VariableB ==
Variable.*?==
matches the word "Variable" followed by "==" somewhere on the same line (the expression .*?
matches anything except newlines). The preceding expression [\s\S]*?
(shortest match of any character including newlines) makes sure that the next occurrence of the word "Version" after the word "Name2" is matched.
Upvotes: 1