PowerShell: Use Format-Table and Control Column Width


Often you may want to use the Format-Table cmdlet in PowerShell to create a table and specify the width of columns in the table.

You can use the following methods to do so:

Method 1: Use Format-Table with AutoSize Parameter

Get-Service | Format-Table -AutoSize

The -AutoSize parameter ensures that each column is as wide as it needs to be in the table to display the longest value in each column.

Method 2: Use Format-Table with Width Parameter

Get-Service | Format-Table -Property @{ e='Name'; width=8 }, DisplayName

This particular example uses the width parameter to specify that the column named Name should only show the first 8 characters of each string, while the DisplayName column should simply show the default number of characters.

The following examples show how to use each method in practice.

Example 1: How to Use Format-Table with AutoSize Parameter in PowerShell

Suppose that we use the Get-Service cmdlet to get a list of all services on our computer and then use the Format-Table cmdlet to display the services in a table:

Get-Service | Select -First 15 | Format-Table

The following screenshot shows how to use this syntax in practice:

Notice that some of the strings in the Name column are cut off.

To force each column in the table to be as wide as it needs to be to display the longest string, we can use the -AutoSize parameter as follows:

Get-Service | Select -First 15 | Format-Table -AutoSize

The following screenshot shows how to use this syntax in practice:

PowerShell Format-Table control width of each column with autosize

Notice that the Name column is now as wide as it needs to be to display the full string in each row.

Example 2: How to Use Format-Table with Width Parameter in PowerShell

We can also use the width parameter to specify that the column named Name should only show the first 8 characters of each string, while the DisplayName column should simply show the default number of characters:

Get-Service | Select -First 15 | Format-Table -Property @{ e='Name'; width=8 }, DisplayName

The following screenshot shows how to use this syntax in practice:

PowerShell Format-Table control width

Notice that the Name column is cut off to only display 8 characters while the DisplayName column has an unchanged width.

Note: You can find the complete documentation for the Format-Table cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Sort a Table with Format-Table
PowerShell: How to Use Format-Table with No Header
PowerShell: How to Remove Elements from a Hash Table

Leave a Reply