PowerShell: How to Convert Text File to CSV File


Often you may want to use PowerShell to convert a text file to a CSV file.

You can use the following basic syntax to do so:

Import-Csv players.txt -delimiter " " | Export-Csv players_new.csv -NoType

This particular example converts the text file named players.txt to a CSV file named players_new.csv.

Here is how this code works:

  • First, we use the Import-Csv cmdlet to import the text file as a “CSV” file with the delimiter being spaces.
  • Next, we use the Export-Csv cmdlet to export this file to a new CSV file.
  • We use the parameter -NoType to specify that no #TYPE information should be displayed as the first line of the exported CSV file.

Note that we used the -delimiter parameter to specify that the delimiter of the text file is a space but you can also specify any other delimiter that you’d like such as a tab, a | symbol, etc.

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

Example: How to Convert Text File to CSV File Using PowerShell

Suppose that we have a text file named players.txt in our current directory that contains information about various basketball players.

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

We can see that the text file uses single spaces to separate the values in each row.

We can use the following syntax to convert this text file to a CSV file named players_new.csv:

Import-Csv players.txt -delimiter " " | Export-Csv players_new.csv -NoType

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

PowerShell convert text file to CSV file

Notice that when we use the Get-Content cmdlet to view the contents of the players_new.csv file we can see that the content from the text file has been successfully converted to comma separated values in a new CSV file.

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 List Files in Directory by Date
PowerShell: How to Get Most Recently Modified File in Directory
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply