PowerShell CSV Data
CSV is a text format that stores rows of data with values split by commas. The first row names each column, and each later row holds one record.
Write a file and read it back
Export-Csv writes the rows to a file. Import-Csv reads them back as objects.
$people = @(
[PSCustomObject]@{ Name = "Ana"; Age = 31 }
[PSCustomObject]@{ Name = "Ben"; Age = 28 }
)
$path = Join-Path $PSScriptRoot "people.csv"
$people | Export-Csv -Path $path -NoTypeInformation
$back = Import-Csv -Path $path
$back[0].Name
$back[1].NameConvert CSV text without a file
ConvertTo-Csv makes the same text in memory. ConvertFrom-Csv turns that text back into objects.
$people = @(
[PSCustomObject]@{ Name = "Ana"; Age = 31 }
[PSCustomObject]@{ Name = "Ben"; Age = 28 }
)
$text = $people | ConvertTo-Csv -NoTypeInformation
$text
$fromCsv = $text | ConvertFrom-Csv
$fromCsv[1].NameCheck a round trip by joining names
Join the names before and after the round trip. If both joined strings match, nothing was lost.
$people = @(
[PSCustomObject]@{ Name = "Ana"; Age = 31 }
[PSCustomObject]@{ Name = "Ben"; Age = 28 }
)
$path = Join-Path $PSScriptRoot "people.csv"
$people | Export-Csv -Path $path -NoTypeInformation
$back = Import-Csv -Path $path
$original = ($people | Select-Object -ExpandProperty Name) -join ", "
$roundTrip = ($back | Select-Object -ExpandProperty Name) -join ", "
$original
$roundTrip
$original -eq $roundTripExample
$people = @(
[PSCustomObject]@{ Name = "Ana"; Age = 31 }
[PSCustomObject]@{ Name = "Ben"; Age = 28 }
[PSCustomObject]@{ Name = "Eli"; Age = 24 }
)
$path = Join-Path $PSScriptRoot "people.csv"
$people | Export-Csv -Path $path -NoTypeInformation
$back = Import-Csv -Path $path
($back | Select-Object -ExpandProperty Name) -join ", "
$original = ($people | Select-Object -ExpandProperty Name) -join ", "
$roundTrip = ($back | Select-Object -ExpandProperty Name) -join ", "
$original -eq $roundTripKey points
- Export-Csv: Use Export-Csv to write objects to a CSV file, one row per object.
- NoTypeInformation: The -NoTypeInformation switch leaves out the extra type line at the top of the file.
- Import-Csv: Use Import-Csv to read a CSV file back into objects.
- Property reads: Each object read back has one property per column, read with a dot.
- In-memory forms: ConvertTo-Csv and ConvertFrom-Csv do the same work on text, with no file involved.
In this example, three rows are written to a file and read back. The joined names show the rows came back, and the comparison confirms the names match the originals exactly.
Note
Values read back from CSV are text, even when they looked like numbers before.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which cmdlet reads a CSV file back into objects?