Creating Reports And Formatting Output In PowerShell

In PowerShell there are a few ways to format your output, in this post I’m going to tie together a few ideas creating reports and formatting output in PowerShell.

Formatting output for the console
The Format-* cmdlets are used to format output and works best for the console window or any display using fixed width font. You can store the formatted output in a variable and you can write it to a text file for instance and keep the format. If you want to iterate over the lines of the formatted text object you can use the Out-String cmdlet to convert it to an array of strings. For example Format-Table will produce output like this:

Creating Reports And Formatting Output In PowerShell

There is also Format-List to list item properties per line and Format-Wide among others, play around with them to see how it looks.

Converting output to HTML
If you need output fit for reporting or email purposes you have to convert it to HTML. Luckily this functionality is already in PowerShell with the ConvertTo-* cmdlets and specifically for HTML the ConvertTo-HTML cmdlet. Obviously the default HTML has no styling and looks pretty dull but you have some control over the HTML generated. You can add CSS to the HTML by specifying a custom Head section. The script below is using an inline style sheet to keep it with the script but you can point to external CSS files as well.

$css = "<title>Files</title>
<style>
table { margin: auto; font-family: Arial; box-shadow: 10px 10px 5px #777; border: black; }
th { background: #0048e3; color: #eee; max-width: 400px; padding: 5px 10px; }
td { font-size: 10px; padding: 5px 20px; color: #111; }
tr { background: #e8d2f3; }
tr:nth-child(even) { background: #fae6f5; }
tr:nth-child(odd) { background: #e9e1f4; }
</style>"

dir | Select-Object -Property Name,LastWriteTime | ConvertTo-Html -Head $css | Out-File C:\Temp\report.html

It generated the following HTML:

Creating Reports And Formatting Output In PowerShell

Convert output for data transfer purposes
If you need the output to be structured for data transfer or machine input purposes you can convert it using the ConvertTo-JSON/XML/CSV cmdlets. JSON and CSV is pretty straight forward but XML needs some explaining. By default the output will be a XML Document and to get to the actual XML you have to use the OuterXML property od the XML Document. You can change the output mechanism by using the -As {format} parameter that takes the following parameter values:
String: Returns the XML as a single string.
Stream: Returns the XML as an array of strings.
Document: The default that returns a XML Document object.
You can control the inclusion of type information in the XML using the -NoTypeInformation parameter. If you have the requirement to keep the generated output as small as possible you can use JSON and pass in the -Compress parameter to compress the output.

Francois Delport