#PSTip Fixing the output of ConvertTo-Html

When you export PowerShell objects to HTML, using the ConvertTo-Html cmdlet, and HTML links are present as the values of the object, ConvertTo-Html doesn’t render them as HTML links. To illustrate, the following snippet creates a table of all cmdlet names (to save space I selected just the first 3) and their online help version.

$helpTbl = Get-Command -CommandType Cmdlet |
Where-Object {$_.HelpUri} |
Select Name,@{n='HelpUri';e={"<a href='$($_.HelpUri)'>$($_.HelpUri)</a>"}} -First 3 |
ConvertTo-Html

$helpTbl
HTML TABLE
NameHelpUri
Add-Computer<a href='http://go.microsoft.com/fwlink/?LinkID=135194'>http://go.microsoft.com/fwlink/?LinkID=135194</a>
Add-Content<a href='http://go.microsoft.com/fwlink/?LinkID=113278'>http://go.microsoft.com/fwlink/?LinkID=113278</a>
Add-History<a href='http://go.microsoft.com/fwlink/?LinkID=113279'>http://go.microsoft.com/fwlink/?LinkID=113279</a>

Notice that some characters were converted into HTML character entities. Character entities are special reserved characters in HTML. In our example, the less than (<), greater than (>), or (‘) signs were converted into their respective entities so the browser can display them ‘as-is’ and not mix them with HTML tags.

That’s nice but it defeats our purpose of making the links clickable. Here’s how the links look when exported to a web page:

There is no parameter on the ConvertTo-Html cmdlet to prevent the conversion from happening. To resolve that we can use the HtmlDecode method to convert the entities back to their HTML equivalents.

To use the HtmlDecode method we first need to load the System.Web assembly.

Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlDecode($cmd)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML TABLE</title> </head><body> <
table> <colgroup><col/><col/></colgroup> <tr><th>Name</th><th>HelpUri</th></tr> <tr><td>Add-Computer</td><td><a href='http://go.microsoft.com/fwlink/?LinkID=135194'>http://go.microsoft.com/fwlink/?LinkID
=135194</a></td></tr> <tr><td>Add-Content</td><td><a href='http://go.microsoft.com/fwlink/?LinkID=113278'>http://go.microsoft.com/fwlink/?LinkID=113278</a></td></tr> <tr><td>Add-History</td><td><a href='
http://go.microsoft.com/fwlink/?LinkID=113279'>http://go.microsoft.com/fwlink/?LinkID=113279</a></td></tr> </table> </body></html>

The output is not as pretty as ConvertTo-Html output but it does exactly what we wanted to–no HTML entities are present. Let’s have a look of the result in a browser:

$helpTbl = Get-Command -CommandType Cmdlet |
Where-Object {$_.HelpUri} |
Select Name,@{n='HelpUri';e={"&lt;a href='$($_.HelpUri)'&gt;$($_.HelpUri)&lt;/a&gt;"}} -First 3 |
ConvertTo-Html

Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlDecode($helpTbl) | Out-File d:\temp\PSCommands.html
Invoke-Item d:\temp\PSCommands.html

Share on: