PowerShell: How to Add Column to CSV


Often you may want to use PowerShell to add a column to an existing CSV file.

Fortunately this is easy to do by using the following syntax:

Import-Csv $my_file |
Select-Object *,@{Name='rebounds';Expression={'0'}} |
Export-Csv nba_data_new.csv -NoTypeInformation

This particular example will add a column named rebounds with a default value of 0 to the existing CSV file located at the path specified by the $my_file variable and save the results to a new CSV file named nba_data_new.csv.

The following example shows how to use this syntax in practice.

Example: How to Add Column to CSV File Using PowerShell

Suppose we have a CSV file saved in the following location:

  • c:\users\bobbi\nba_data.csv

We can use the Get-Content cmdlet to view the contents of this file:

We can see that the file currently has three columns: team, points, and assists.

Suppose that we would like to add a new column to the CSV file named rebounds with a default value of 0 for each row.

We can use the following syntax to do so:

$my_file = "c:\users\bobbi\nba_data.csv"

Import-Csv $my_file |
Select-Object *,@{Name='rebounds';Expression={'0'}} |
Export-Csv nba_data_new.csv -NoTypeInformation

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

PowerShell add column to CSV file

We can see that a new column named rebounds has been added to the CSV file with a default value of 0 for each row.

Note: When using Export-Csv we included -NoTypeInformation to remove the extra file information that would otherwise appear in the header of the CSV file.

Related Tutorials

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

PowerShell: How to Use Export-Csv with No Headers
PowerShell: How to Use Export-Csv with No Quotes
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply