Avoid Format-… in Scripts

by Jun 29, 2009

The family of Format-… Cmdlets is useful for outputting data into the console. You probably often used lines like this:

Get-Service | Format-Table Name

Be aware that Format-… Cmdlets change the objects and return a formatting object used for displaying object data inside the console. You cannot mix different formats. Mixing formats is no issue in a single command but once you start using scripts, you can cause serious trouble.

For example, the following simple script, saved as test.ps1 and then run, will raise an ugly exception:

Dir | Format-Table Name

Reason is: Get-Process was specified without an explicit formatter cmdlet so PowerShell picked its own default formatter. In the second line, you explicitly specified a formatter. PowerShell cannot mix them and since the second formatter is different from the first, you get the exception.

To work around this, you would have to make sure all cmdlets use the same formatter, for example:

Get-Process | Format-List Name
Dir | Format-Table Name

As a general rule of thumb, in scripts it is often better to replace formatter cmdlets with select-object. Select-Object will not turn objects into formatting data but instead limit the objects to only the properties you specified.

Get-Process | Format-Table Name