PowerShell: How to Reorder Columns in CSV File

Often you may want to use PowerShell to reorder columns in a CSV file.

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

Import-Csv input_file.csv |
Select-Object col3, col4, col1, col2 |
Export-Csv output_file.csv

Here is what this particular example does:

  • First, use Import-Csv to import the columns from input_file.csv.
  • Then, use Select-Object to select columns in a specific order.
  • Then, use Export-Csv to export this data in this specific column order to a file named output_file.csv.

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

Example: How to Use PowerShell to Reorder Columns in CSV File

Suppose we have a CSV file named nba_data.csv in our current directory that contains information about various basketball players.

We can use the Import-Csv cmdlet to view the contents of this file:

Notice that the columns in the file are currently in the following order:

  • team, points, assists, rebounds

Suppose instead that we would like to create a new CSV file with the following order:

  • assists, team, points, rebounds

We can use the following syntax to do so:

Import-Csv nba_data.csv |
Select-Object assists, team, points, rebounds |
Export-Csv nba_data_new.csv

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

PowerShell reorder CSV columns

Notice that when we use the Import-Csv cmdlet to view the contents of the new file named nba_data_new.csv we can see that the columns are in the exact order that we specified:

  • assists, team, points, rebounds

Note: You can find the complete documentation for the Export-Csv cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Get Values from Header of CSV
PowerShell: How to Loop Through Each Line of CSV File
PowerShell: How to Count Number of Rows in CSV File

Leave a Reply