HTML Bits and Pieces, Part 1

One of the handiest cmdlets in PowerShell, especially when it comes to report generation, is ConvertTo-HTML. This cmdlet will take any object you pipe to it and create an html table. Technically the cmdlet creates the HTML code to create the table. You need to pipe to Out-File to save the result:

Figure 2. The results are easier to read here, but we can take it a step further. (Click image to view larger version.)

Better. Let's keep at it. It would be nice to include a title, which, as luck would have it, we can specify with the -Title parameter. We can also apply style by referencing a style sheet. The location you specify depends on where and how your file will be viewed. If you are viewing this on your computer, then use a path relative to it. If you are going to view on an intranet, then put the style sheet where everyone can access it. Here's my next iteration:

One thing to watch for with this approach is that you need to put the title in the header code. But otherwise you get the same result and the style goes with the document.

The last bits I want to go over this time are how to insert additional content to the document. Remember, the input objects are turned into a table. However, you can also insert text before and after the table using the -PreContent and -PostContent parameters. Well, technically what you are inserting is HTML code, but let's not quibble. Here's what it looks like:

I only grabbed the first 10 services so you could see the pre/post content in Figure 4.

Figure 4. A simple HTML report showing the first 10 results with some descriptive text before and after the table. (Click image to view larger version.)

The main point to remember with ConvertTo-HTML is to control what properties you want to display and send the results to a text file. But what if you don't want a table? Or what if you want several tables in the same document? We'll cover that in the next lesson.

About the Author

Jeffery Hicks is a multi-year Microsoft MVP in Windows PowerShell, Microsoft Certified Professional and an IT veteran with almost 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He works today as an independent author, trainer and consultant. Jeff is a regular contributor to a variety on online sites, as well as frequent speaker at technology conferences and user groups. Keep up with Jeff and his projects at http://jdhitsolutions.com/blog.