Thomas Lang
Thomas Lang

Reputation: 231

fill an array with variables with a loop

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
        }
    }
}

Upvotes: 1

Views: 689

Answers (1)

henrycarteruk
henrycarteruk

Reputation: 13227

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' }

Upvotes: 1

Related Questions