ConvertTo-Html

Converting Objects to Beautiful HTML with ConvertTo-Html

Welcome back to Wahmans Powershell Blog! Today we’re diving into a very handy cmdlet for anyone looking to present data in a clean, readable format for the web. Say hello to ConvertTo-Html — a powerful tool in the PowerShell toolbox that lets you transform .NET objects into HTML tables.

As Microsoft Docs describes it: “Converts .NET objects into HTML that can be displayed in a Web browser.”

Let’s look at how you can use this cmdlet in progressively more advanced scenarios!

Example 1: Basic HTML Table of Processes

This first one is great if you’re just getting your feet wet. Let’s create a basic HTML table from Get-Process output.

Get-Process | ConvertTo-Html | Out-File processes.html

This will create an HTML file named processes.html containing a table of all currently running processes.

Example 2: Include a Styled Header

Adding a title and using inline CSS helps make your HTML output more readable.

Get-Service | 
ConvertTo-Html -Property Name, Status, DisplayName -Head "<style>table {font-family: Arial; border-collapse: collapse;} td, th { border: 1px solid #ddd; padding: 8px; }</style>" -Title "Service Report" | 
Out-File services.html

This generates a well-formatted service table with a title and some basic CSS for styling.

Example 3: Email Report with HTML Body

You can even use ConvertTo-Html to send HTML-formatted reports via email.

$html = Get-EventLog -LogName Application -Newest 10 | 
ConvertTo-Html -Property TimeGenerated, EntryType, Source, Message -Title "Latest Application Events"

Send-MailMessage -To "[email protected]" -From "[email protected]" -Subject "Daily Application Log" -BodyAsHtml -Body $html -SmtpServer "smtp.example.com"

Now your logs can arrive in your inbox in neatly formatted tables!

Example 4: Multiple Tables in One HTML Report

For more advanced use, you can create a dashboard-like HTML file that includes multiple data sets.

$procHtml = Get-Process | ConvertTo-Html -Property Name, Id, CPU -Fragment -PreContent "<h2>Running Processes</h2>"
$svcHtml = Get-Service | ConvertTo-Html -Property Name, Status -Fragment -PreContent "<h2>Services</h2>"

$fullHtml = @"
<html>
<head>
<style>
table { font-family: Calibri; border-collapse: collapse; width: 100%; }
th, td { border: 1px solid black; padding: 5px; text-align: left; }
</style>
</head>
<body>
$procHtml
$svcHtml
</body>
</html>
"@

$fullHtml | Out-File systemReport.html

This approach gives you finer control over the layout and content of your HTML reports.

Wrapping Up

Whether you’re preparing reports, generating dashboards, or creating formatted email body content, ConvertTo-Html is a powerful cmdlet that can make your scripts look impressive and polished.

Happy scripting, and I will see you in the next post!

Leave a Reply

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