0

I have a log file that has a lot of fields listed in it. I want to extract the fields out of the file, but I don't want to search through the file line by line.

I have my pattern:

$pattern="Hostname \(Alias\):(.+)\(.+Service: (.+)"

This will give me the two values that I need. I know that if I have a string, and I'm looking for one match I can use the $matches array to find the fields. In other words, If I'm looking at a single line in the file using the string variable $line, I can extract the fields using this code.

if($line -matches $pattern){
  $var1=$matches[1]
  $var2=$matches[2]
}

But how can I get these values without searching line by line? I want to pass the whole file as a single string, and add the values that I am extracting to two different arrays.

I'm looking for something like

while($filetext -match $pattern){
  $array1+=$matches[1]
  $array2+=$matches[2]
}

But this code puts me in an infinite loop if there is even one match. So is there a nextMatch function I can use?

1 Answer 1

2

PowerShell 2.0 addressed this limitation by adding the -AllMatches parameter to the Select-String cmdlet e.g.:

$filetext | Select-String $pattern -AllMatches | 
    Foreach {$_.Matches | Foreach {$_.Groups[1] | Foreach {$_.Value}}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.