Working with CSV Files in PowerShell

If you’re working with data from PowerShell, you have most likely come across the CSV (Comma Separate Values) format. These files are very easy to work with in PowerShell, thanks to the CSV cmdlets. If this is your first time working with CSV files, it’s easy to discover the CSV-related commands in PowerShell.

PowerShell: CSV Files
PowerShell: CSV Files

Create Some CSV Data

To start off, let’s use PowerShell to create some test data, in CSV format, to work with.

Read the CSV Data

Using the Import-Csv core PowerShell command, we can easily import the file that we just created. If we use the Get-Member cmdlet to “reflect” on the objects we imported, we can see that we have an array of PSCustomObject instances. If your CSV file uses a different character, than a comma, to separate the data fields, you can add the -Delimiter parameter to your call to Import-Csv.

Exporting Objects as CSV

You can take arbitrary objects in PowerShell and export them to a CSV file. For example, you can take an array of Windows processes and export the details to a CSV file. You can also take an array of Windows Services, Exchange mailboxes, Azure Virtual Machines, or any object, and export it to a CSV file. We use the Export-Csv command to achieve this. By default, the Export-Csv command adds a line that denotes the type of object that is being exported. To ensure a clean export however, you can add the -NoTypeInformation parameter to Export-Csv to suppress this output.

Conversion

You can convert objects to/from CSV without using the filesystem. To achieve this, there are two PowerShell commands: ConvertTo-Csv and ConvertFrom-Csv. These commands perform essentially the same task as the Export/Import-Csv commands, but they don’t write or read data from a file.