Creating HTML report with CSS (Cascading Style Sheet) using Powershell

All Tech/non Tech peoples loves a nice HTML report for reviewing. Creating these type of reports in PowerShell is very easy and simple. These type of nice HTML reports can be generate with the help ConvertTo-HTML cmdlet. Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser. The ConvertTo-HTML does not create an actual file, just the HTML code.This means that we can modify the HTML on the fly and save the file when finished. 

For this simple report i had used only few properties like -CssUri , -Postcontent and -PreContent from the ConvertTo-HTML cmdlet.

Pre/Post Content

Usually we will create table and generate content with the help of ConvertTo-HTML cmdlet. But if you want to insert additional HTML directives to put in before and after the main code. This can be achieve using “-PreContent” and “-PostContent” cmdlet.

-PreContent : Specifies text to add before the starting tag. By default, there is no text in that position

-PostContent : Specifies text to add after the closing tag. By default, there is no text in that position

CssUri

Specifies the Uniform Resource Identifier (URI) of the cascading style sheet (CSS) that is applied to the HTML file. The URI is included in a style sheet link in the output.

Final code:

Here i had wrote the required CSS code for the report and placed the below code in notepad and saved with the name C:\dotnet-helpers\design.css. The same CSS will be called during the report generation. So the style will be applied to the final HTML report.

body { background-color:#E5E4E2;
font-family:Monospace;
font-size:10pt; }
table,td, th { border:1px solid black;}
th { color:#00008B;
background-color:white; 
font-size: 12pt;}

table { margin-left:30px; }
h2 {
font-family:Tahoma;
color:#6D7B8D;
}
h1{color:#DC143C;}
h5{color:#DC143C;}

In the below script I’m adding style from an external CSS file with help of -CssUri parameter (-CssUri ‘C:\temp\design.css’) and generating the HTML report in the destination location. The CSS from the file will applied to the HTML element during the execution and generate the report as like below.

Get-Eventlog -List | Select @{Name="Logs";Expression = {$_.LogDisplayname}} , 
@{Name="Entries";Expression = {"{0:n0}" -f $_.entries.count}} |
#Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser.
#the Title, Body, PreContent, and PostContent parameters of ConvertTo-Html to customize the output..
convertto-html -Title "Daily Log Report" -PreContent "<H1>Daily Event Log Report : $($env:COMPUTERNAME)</H1>" -PostContent "<H5><i>Copy right @ dotnet-helpers.com</i></H5>" -CssUri 'C:\dotnet-helpers\design.css' |
Set-Content C:\dotnet-helpers\DailyLogReport.htm

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.