PJC83
PJC83

Reputation: 303

ForEach loop results in a single HTML table

Below is a simplified version of a code I use to check different folders, check the most recent log file, and then report the most recent 3 timestamps (denoted by [).

$LogLocations = "C:\Powershell\Test\Scenario1",
                "C:\Powershell\Test\Scenario2"

$style = @"
<style>BODY{font-family: Arial; font-size: 10pt;}
TABLE{border: 1px solid black; border-collapse: collapse;}
TH{border: 1px solid black; background: #dddddd; padding: 5px; }
TD{border: 1px solid black; padding: 5px; }
</style>
"@

$body = ""

foreach ($logpath in $LogLocations) {
    $log  = Get-ChildItem -Path $logpath |
            sort LastWriteTime |
            select -ExpandProperty FullName -Last 1
    $text = Get-Content -Path $log |
            Select-String -SimpleMatch "[" |
            select Line -Last 3
    $body += ($text |
             select Line |
             ConvertTo-Html -Body "<p>Timestamps of 3 most recent files processed $log</p>" -Head $style |
             Out-String)
}

$emailbody = ConvertTo-Html -PostContent $body | Out-String
$subject = "Processing Logs Error Checking at " + (Get-Date -Format g)

Send-MailMessage -From "xxxxxxxxx" -To "xxxxxxxxx" -Subject $subject -Body $emailbody -BodyAsHtml -SmtpServer "xxxxxxxxx"

The result I get is:

Timestamps of 3 most recent files processed C:\Powershell\Test\Scenario1\20160520163102.txt
*
[05/21/2016 00:37:52]
[05/21/2016 00:37:52]
[05/21/2016 00:37:52]
Timestamps of 3 most recent files processed C:\Powershell\Test\Scenario2\20160524142045.txt
*
[05/24/2016 14:38:48]
[05/24/2016 14:38:51]
[05/24/2016 14:38:51]

which is fine. I get the info I want, it's just that the formatting isn't the greatest. I've tried to find a way to put the results in the same table, but cannot get the code to work, I will either get errors, no results, or horribly formatted results.

Any ideas? I was going down the route of nesting the current foreach statement inside another foreach statement for table columns.

Upvotes: 0

Views: 1143

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

If you don't want multiple tables, don't create multiple tables.

$emailbody = $LogLocations | ForEach-Object {
    $dir = $_
    Get-ChildItem $dir |
        Sort-Object LastWriteTime |
        Select-Object -Last 1 |
        Get-Content |
        Where-Object { $_ -like '*[*' } |
        Select-Object -Last 3 @{n='File';e={$dir.FullName}},
            @{n='Timestamp';e={$_}}
} | ConvertTo-Html -Head $style

Upvotes: 1

Related Questions