Powershell – Compare an element of an array with the previous element in PowerShell

log-filespowershell

Can someone describe a good pattern to compare $entry[X] to $entry[Y] to determine if they are the same? I'm trying to get readable summaries of my logs and don't want to spit out 400 identical lines.

foreach ($log in $logs) {

    $nm = $log.LogDisplayName

    $header = $log.LogDisplayName
    Write-Host $header
    Add-Content $output "$header Log Errors/Warnings, Past 48 Hours"

    $entries = $log.Entries | ? {$_.TimeWritten -gt ($(Get-Date).AddDays(-2)) -and (($_.EntryType -like "Error") -or ($_.EntryType -like "Warning"))}

    foreach ($entry in $entries) { 


        ***here is where I think I need to compare array elements***


    }


    out-string -inputobject $entries | add-content $output

Best Answer

To compare the current entry to the previous one:

$preventry = ""
$newarray = $()
foreach ($entry in $entries) {
    if ($entry -ne $preventry) { $newarray += @($entry) }
    $preventry = $entry
}

The resulting array $newarray contains all the contents of $entries but with the adjacent duplicates removed.