Reputation: 231
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
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