1

I have converted a log file to an array, some elements in array contain the keyword Messages. I want a new array that only contains elements with that keyword.

I tried the following:

$Logfile_array = Get-Content "C:\temp\logfiles\complete_log.txt"
foreach ($array_element in $Logfile_array)
{
    if ($array_element -match 'Messages')
    {
        foreach ($array_element in $Logfile_array)
        {
          $i++
          echo $i
          $array_message[$i] = $array_element
        }
    }
}
2
  • So you add the first message once, the second twice and so on. Is that what you intended? Commented Jul 4, 2018 at 10:06
  • What is $array_element supposed to be in the inner loop, when you also use it in the outer loop? Commented Jul 4, 2018 at 10:09

1 Answer 1

1

Instead of using foreach to loop through the array and then checking each item, you can use Where-Object to do this for you:

$Logfile_array = Get-Content "C:\temp\logfiles\complete_log.txt"
$array_message = $Logfile_array | Where-Object { $_ -match 'Messages' }

or a one liner:

$array_message = Get-Content "C:\temp\logfiles\complete_log.txt" | Where-Object { $_ -match 'Messages' }
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.