Chapter 12. Creating custom format views

 

We’re getting back to the script that we left off with in chapter 10, before our short diversion into the world of debugging. One thing we didn’t like about that script was its output. Some folks would be tempted to put commands right into the script to fix that, but we know better. Remember: A tool should either create input for another tool, do something, or format output from another tool. Our tool is already doing something, so we can’t have it start messing around with formatting the output as well. Instead, we’ll get PowerShell to do that for us by creating a custom view.

12.1. The anatomy of a view

PowerShell ships with a number of views, all of which are contained in .format.ps1xml files that live within PowerShell’s installation folder. You can get there by running cd $pshome in the shell, and we’ll open DotNetTypes.format.ps1xml in Notepad (or the ISE) to view it.

Caution

Be very careful not to make any changes to the .format.ps1xml files in PowerShell’s installation folder—or if you do, make sure you don’t save those changes. The files are digitally signed, and even an extra space or carriage return will break them, rendering them useless to PowerShell.

There’s a lot of stuff in there, but let’s just start with a simple table view:

Here’s what we’d like you to notice:

12.2. Adding a type name to output objects

12.3. Making a view

12.4. Loading and debugging the view

12.5. Using the view

12.6. Coming up next

12.7. Labs