PowerShell Tip: Formatting Output

In PowerShell everything is a .NET object, each with a variety of different properties. You’ll notice that most of the time the output you see from basic commands only gives you a small subset of what’s available. This is because PowerShell has built-in rules for how and what to display for most of the standard objects. Usually this is done so that you normally only see what’s most important and aren’t overwhelmed with too much data. For example, the dir command returns a set of FileSystemInfo objects but only shows you a few of the 20+ properties that are available.

Screen shot 2010 07 12 at 8.57.21 AM

You can override the default output for any object and PowerShell provides a set of cmdlets for just this purpose: Format-Wide, Format-Table, Format-List, and Format-Custom. I’ll cover Format-Custom in another post, so for now here’s a brief description of the first 3.

Format-Wide

This cmdlet simple takes one property of each object and writes them out across the window. This is similar to the /w option when using dir in cmd.exe.

Screen shot 2010 07 12 at 9.02.42 AM

Notice that to use the cmdlet you need to pipe the output of the dir command to Format-Wide. Unlike the pipe command in cmd.exe, you aren’t just sending the text from the first command but actual .NET objects which allows the second command to have full control when dealing with them.

With Format-Wide you can select the property to show with the -Property parameter. You can also adjust the width of the columns with -Column.

Screen shot 2010 07 12 at 9.06.21 AM

Format-Table

This cmdlet formats objects just like the default dir command, but you have control over what properties show up and how they are formatted. For example:

Screen shot 2010 07 12 at 9.17.21 AM

In order to adjust the widths of the columns independently you need to create a View and pass it to the cmdlet, but that’s a topic for its own posting. You can even group the output by unique properties of the files.

Screen shot 2010 07 12 at 9.26.39 AM

Format-List

This cmdlet formats the output as a list of properties. It’s similar to the table output, but rotated 90 degrees.

Screen shot 2010 07 12 at 9.29.09 AM

Just like Format-Table you can decide which properties to show. You can use wildcards to select multiple properties (this also works with Format-Table.)

Screen shot 2010 07 12 at 9.31.35 AM

If you just use * for the property list you’ll see all of the properties of the object. This is handy while exploring objects to see what information you can work with.

Hopefully this quick overview will get you exploring the different ways to output data in PowerShell. In future posts I’ll discuss more advanced topics such as Format-Custom, Views, and Calculated Properties.