How to Import Text File and Format and Export It to CSV in PowerShell

John Wachira Feb 02, 2024
How to Import Text File and Format and Export It to CSV in PowerShell

This article outlines how we can import a text file and format and export it to a CSV file with PowerShell.

PowerShell commands like Get-Content, ConvertFrom-StringData, and Export-Csv come in handy when you want to import files and export them as CSV files. If you are unsure how this is done, stick around, we have a lot to unpack.

Import Text File and Format and Export It to CSV in PowerShell

For easier context, we will use an example.

Let’s assume the image below represents the content of the text file we wish to import, format, and export to a CSV file. How would we go about it?

Text file

The first step is to parse the data into a custom object, making it easier to process. Below is the script we will use:

$usrObj = [pscustomobject] ((Get-Content -Raw C:\Users\pc\Demo\Users.txt) -replace ':', '=' |
        ConvertFrom-StringData)

We use -replace ':', '=' to change the : to = since ConvertFrom-StringData only accepts = as the separator between a key and its corresponding value.

Additionally, we use [pscustomobject] to convert the hashtable generated by ConvertFrom-StringData into a custom object.

We can further format this into a table in our desired order with the script below:

$usrObj | Format-Table 'Username', 'Title', 'Department', 'Manager', 'Similar User'

This will yield the following output:

Format table

We can then save the information in a CSV file called Users.csv. Below is the script we will use:

$usrObj | Export-Csv -NoTypeInformation -Encoding Utf8 Users.csv

Our CSV file should look like this:

Initial CSV File

In conclusion, you can import and export a text file as a CSV file on PowerShell. Commands like Get-Content, ConvertFrom-StringData, and Export-Csv come in handy in such scenarios.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - PowerShell CSV