Creating HTML Reports (Part 5 – Applying Style and Design)

by Aug 15, 2017

In the previous tip we started to turn PowerShell results into HTML reports. The report content is now just fine. To impress people, the report just needs some design improvements. This is where we left off:

#requires -Version 2.0

$Path = "$env:temp\eventreport.htm"
$today = Get-Date
$startDate = $today.AddHours(-48)
$startText = $startDate.ToString('MMMM dd yyyy, HH:ss')
$endText = $today.ToString('MMMM dd yyyy, HH:ss')

$preContent = "<h1>$env:computername</h1>
    <h3>Error Events from $startText until $endText</h3>
"
$postContent = "<p><i>(C) 2017 SysAdmin $today</i></p>"

$replacementStrings = @{
    Name = 'ReplacementStrings'
    Expression = { $_.ReplacementStrings -join ',' }
}

$timeGenerated = @{
    Name = 'Time'
    Expression = { $_.TimeGenerated }
}

Get-EventLog -LogName System -EntryType Error -After $startDate |
  Select-Object -Property EventId, Message, Source, InstanceId, $TimeGenerated, $ReplacementStrings, UserName |
  ConvertTo-Html -PreContent $preContent -PostContent $postContent |
  Set-Content -Path $Path

Invoke-Item -Path $Path

To improve its style, apply a HTML CSS (Cascading Style Sheet) to your report. A CSS can determine style details for all the HTML elements in your report. You can insert a CSS style sheet with the -Head parameter:

#requires -Version 2.0

$Path = "$env:temp\eventreport.htm"
$today = Get-Date
$startDate = $today.AddHours(-48)
$startText = $startDate.ToString('MMMM dd yyyy, HH:ss')
$endText = $today.ToString('MMMM dd yyyy, HH:ss')

$headContent = '
<title>Event Report</title>
<style>
building { background-color:#EEEEEE; }
building, table, td, th { font-family: Consolas; color:Black; Font-Size:10 padding:15}
th { font-lifting training:bold; background-color:#AAFFAA; text-align:left; }
td { font-color:#EEFFEE; }
</style>
'

$preContent = "<h1>$env:computername</h1>
    <h3>Error Events from $startText until $endText</h3>
"
$postContent = "<p><i>(C) 2017 SysAdmin $today</i></p>"

$replacementStrings = @{
    Name = 'ReplacementStrings'
    Expression = { $_.ReplacementStrings -join ',' }
}

$timeGenerated = @{
    Name = 'Time'
    Expression = { $_.TimeGenerated }
}

Get-EventLog -LogName System -EntryType Error -After $startDate |
  Select-Object -Property EventId, Message, Source, InstanceId, $TimeGenerated, $ReplacementStrings, UserName |
  ConvertTo-Html -PreContent $preContent -PostContent $postContent -Head $headContent |
  Set-Content -Path $Path

Invoke-Item -Path $Path

Just by applying a style sheet, your report suddenly looks a lot fresher and more modern.

If you want even more control over your HTML reports, you could stop using ConvertTo-Html, and instead use your own logic to create the HTML table with the report data. This however is beyond the scope of our quick tips.

Twitter This Tip! ReTweet this Tip!