DEV Community

Cover image for Export Data to CSV in PowerShell: Export-Csv Explained
arnostorg
arnostorg

Posted on Edited on

Export Data to CSV in PowerShell: Export-Csv Explained

Someone asks for "a list of the files in that folder, in Excel, by lunch". In PowerShell that is one pipeline: pick the columns with Select-Object, then hand the objects to Export-Csv. Each object becomes one row, and each property becomes one column.

This tip covers the jobs you will actually use it for: exporting a file list, logging repeated runs, making Excel on a European machine open the file properly, keeping accented names intact, reading the file back, and not overwriting a report you needed. Every snippet below was run in PowerShell 7.4, and the output shown is the real output. Where Windows PowerShell 5.1 behaves differently, I say so.

Set up a safe demo folder

Run this first. It creates a throwaway folder in your temp directory with three small files and a fixed timestamp, so your output matches mine:

$demo = Join-Path ([IO.Path]::GetTempPath()) 'export-csv-demo'
New-Item -ItemType Directory -Path (Join-Path $demo 'Logs') -Force | Out-Null
Set-Location -Path $demo
Set-Content -Path .\Logs\app.log -Value 'service started, 3 jobs ok' -NoNewline
Set-Content -Path .\Logs\error.log -Value 'disk full on D:' -NoNewline
Set-Content -Path .\Logs\report.txt -Value 'Quarterly numbers' -NoNewline
Get-ChildItem -Path .\Logs -File | ForEach-Object { $_.LastWriteTime = '2026-11-20 08:15' }
Get-ChildItem -Path .\Logs -File | Select-Object -Property Name, Length
Enter fullscreen mode Exit fullscreen mode
Name       Length
----       ------
app.log        26
error.log      15
report.txt     17
Enter fullscreen mode Exit fullscreen mode

All the later snippets assume you are still inside that folder.

Job 1: Export a file list to CSV

Select the properties you want first, then export:

Get-ChildItem -Path .\Logs -File |
    Select-Object -Property Name, Length,
        @{ Name = 'LastWriteTime'; Expression = { $_.LastWriteTime.ToString('yyyy-MM-dd HH:mm') } } |
    Export-Csv -Path .\files.csv

Get-Content -Path .\files.csv
Enter fullscreen mode Exit fullscreen mode
"Name","Length","LastWriteTime"
"app.log","26","2026-11-20 08:15"
"error.log","15","2026-11-20 08:15"
"report.txt","17","2026-11-20 08:15"
Enter fullscreen mode Exit fullscreen mode

Three things to notice:

  • Select-Object decides the columns. Without it you get every property of FileInfo (dozens of columns, such as PSPath, Attributes and Directory).
  • The calculated property turns LastWriteTime into yyyy-MM-dd HH:mm. A raw DateTime is written using your culture's format, which may not sort or parse correctly on someone else's machine.
  • Every value is quoted and written as text. CSV has no types, and that matters when you import the file again (more on that below).

-NoTypeInformation: needed in 5.1, default in 7

In Windows PowerShell 5.1, Export-Csv writes a #TYPE line above the header by default, and Excel shows it as a junk first row. That is why so many scripts end with -NoTypeInformation. Since PowerShell 6.0, no type line is the default, and -NoTypeInformation is accepted but does nothing. If you want the old behavior in 7, you have to ask for it:

# PowerShell 7: opt back in to the old 5.1 default
Get-ChildItem -Path .\Logs -File |
    Select-Object -Property Name, Length |
    Export-Csv -Path .\typed.csv -IncludeTypeInformation

Get-Content -Path .\typed.csv -TotalCount 2
Enter fullscreen mode Exit fullscreen mode
#TYPE Selected.System.IO.FileInfo
"Name","Length"
Enter fullscreen mode Exit fullscreen mode

Rule of thumb: if a script has to run on both versions, keep -NoTypeInformation. It is harmless in 7 and required in 5.1.

Job 2: Append one row per run with -Append

Without -Append, Export-Csv replaces the file without warning. With it, you get a simple run log. The header is written once, and each run adds a row:

foreach ($run in 1..3) {
    [pscustomobject]@{
        Run    = $run
        Files  = (Get-ChildItem -Path .\Logs -File).Count
        Status = 'OK'
    } | Export-Csv -Path .\runs.csv -Append
}

Get-Content -Path .\runs.csv
Enter fullscreen mode Exit fullscreen mode
"Run","Files","Status"
"1","3","OK"
"2","3","OK"
"3","3","OK"
Enter fullscreen mode Exit fullscreen mode

If the new object does not have a property that matches an existing column, PowerShell refuses to append instead of quietly shifting your columns:

try {
    [pscustomobject]@{ Run = 4; Status = 'FAILED' } |
        Export-Csv -Path .\runs.csv -Append -ErrorAction Stop
}
catch {
    $_.Exception.Message
}
Enter fullscreen mode Exit fullscreen mode
Cannot append CSV content to the following file: .\runs.csv. The appended object does not have a property that corresponds to the following column: Files. To continue with mismatched properties, add the -Force parameter, and then retry the command.
Enter fullscreen mode Exit fullscreen mode

Adding -Force overrides this check. Only the matching properties are written, and the mismatched ones are dropped. Use it on purpose, not as a reflex.

Job 3: Make Excel open it in columns (-Delimiter and -UseCulture)

In much of Europe, including Czech and German Windows, the list separator is ; because the comma is the decimal separator. Double-click a comma CSV there and Excel can put every row into column A. You have two fixes.

Set the delimiter explicitly. The semicolon goes in single quotes:

Get-ChildItem -Path .\Logs -File |
    Select-Object -Property Name, Length |
    Export-Csv -Path .\files-excel.csv -Delimiter ';'

Get-Content -Path .\files-excel.csv
Enter fullscreen mode Exit fullscreen mode
"Name";"Length"
"app.log";"26"
"error.log";"15"
"report.txt";"17"
Enter fullscreen mode Exit fullscreen mode

Or let Windows decide with -UseCulture, which uses (Get-Culture).TextInfo.ListSeparator. Here I switch the culture to Czech to show what a Czech machine produces. On a real Czech machine, skip the first line:

[cultureinfo]::CurrentCulture = 'cs-CZ'   # simulate a Czech Windows box
(Get-Culture).TextInfo.ListSeparator

[pscustomobject]@{ Server = 'web01'; FreeGB = 12.5 } |
    Export-Csv -Path .\disk.csv -UseCulture

Get-Content -Path .\disk.csv
Enter fullscreen mode Exit fullscreen mode
;
"Server";"FreeGB"
"web01";"12,5"
Enter fullscreen mode Exit fullscreen mode

Notice that 12.5 was written as 12,5, because numbers are also converted using the current culture. -UseCulture suits files that people open in Excel on the same machine. For files that another script reads, a fixed -Delimiter is more predictable.

Job 4: Keep accents intact (-Encoding utf8BOM)

PowerShell 7 writes UTF-8 without a BOM by default (utf8NoBOM). Excel opens a double-clicked CSV without a BOM in the legacy code page, so Arnošt and Plzeň come out garbled. Adding a BOM fixes that:

$people = [pscustomobject]@{ User = 'Arnošt'; City = 'Plzeň' }

$people | Export-Csv -Path .\users-nobom.csv
$people | Export-Csv -Path .\users-bom.csv -Encoding utf8BOM

foreach ($file in 'users-nobom.csv', 'users-bom.csv') {
    $bytes = Get-Content -Path $file -AsByteStream -TotalCount 3
    '{0,-16} {1}' -f $file, (($bytes | ForEach-Object { '{0:X2}' -f $_ }) -join ' ')
}
Enter fullscreen mode Exit fullscreen mode
users-nobom.csv  22 55 73
users-bom.csv    EF BB BF
Enter fullscreen mode Exit fullscreen mode

EF BB BF is the UTF-8 BOM. The file without it starts directly with "Us (22 55 73).

Windows PowerShell 5.1 is different again. Its Export-Csv defaults to ASCII, so š and ň become ? and the data is lost, not just displayed badly. There is no utf8BOM value in 5.1, but -Encoding UTF8 there writes UTF-8 with a BOM, which is what Excel wants. The about_Character_Encoding page lists the defaults for both versions.

The classic mistake: piping Format-Table into Export-Csv

Format-Table is for the screen. It outputs formatting instructions, not your data, so this is what ends up in the file:

# Don't do this
Get-ChildItem -Path .\Logs -File |
    Format-Table -Property Name, Length |
    Export-Csv -Path .\broken.csv

Get-Content -Path .\broken.csv -TotalCount 2
Enter fullscreen mode Exit fullscreen mode
"ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo","shapeInfo","groupingEntry"
"033ecb2bc07a4d43b5ef94ed5a35d280",,,,"Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo",
Enter fullscreen mode Exit fullscreen mode

There are no file names and no sizes, only formatter internals. The fix is always the same: use Select-Object for the columns and keep Format-* cmdlets at the very end of a pipeline that goes to the screen. I wrote up the full story in PowerShell Select-Object vs Format-Table: why your CSV is full of GUIDs.

Round trip: read it back with Import-Csv

Import-Csv turns each row back into an object with one property per column:

$rows = Import-Csv -Path .\files.csv
$rows | Format-Table

$rows[0].Length.GetType().Name
($rows | Measure-Object -Property Length -Sum).Sum
Enter fullscreen mode Exit fullscreen mode
Name       Length LastWriteTime
----       ------ -------------
app.log    26     2026-11-20 08:15
error.log  15     2026-11-20 08:15
report.txt 17     2026-11-20 08:15

String
58
Enter fullscreen mode Exit fullscreen mode

Note the String. Everything comes back as text, because CSV has no types. Measure-Object happens to convert the values for you, but sorting does not: sorted as text, "9" comes after "26". Cast when you sort:

Import-Csv -Path .\files.csv |
    Sort-Object -Property { [int]$_.Length } -Descending |
    Select-Object -First 1 -ExpandProperty Name
Enter fullscreen mode Exit fullscreen mode
app.log
Enter fullscreen mode Exit fullscreen mode

If you used -Delimiter ';' on export, pass the same -Delimiter ';' to Import-Csv.

Safety: -NoClobber and -Force

By default, Export-Csv overwrites an existing file without asking. When a report must not be replaced, add -NoClobber:

try {
    Get-ChildItem -Path .\Logs -File |
        Select-Object -Property Name, Length |
        Export-Csv -Path .\files.csv -NoClobber -ErrorAction Stop
}
catch {
    "Refused: $($_.FullyQualifiedErrorId)"
}
(Import-Csv -Path .\files.csv)[0].LastWriteTime
Enter fullscreen mode Exit fullscreen mode
Refused: NoClobber,Microsoft.PowerShell.Commands.ExportCsvCommand
2026-11-20 08:15
Enter fullscreen mode Exit fullscreen mode

The original files.csv, with its LastWriteTime column, is untouched. In the other direction, -Force lets Export-Csv overwrite a file marked read-only:

(Get-Item -Path .\files-excel.csv).IsReadOnly = $true

try {
    Get-ChildItem -Path .\Logs -File | Select-Object -Property Name |
        Export-Csv -Path .\files-excel.csv -ErrorAction Stop
}
catch {
    'Without -Force: write blocked'
}

Get-ChildItem -Path .\Logs -File | Select-Object -Property Name |
    Export-Csv -Path .\files-excel.csv -Force
"With -Force: $((Get-Content -Path .\files-excel.csv)[0])"
Enter fullscreen mode Exit fullscreen mode
Without -Force: write blocked
With -Force: "Name"
Enter fullscreen mode Exit fullscreen mode

Read-only was protecting that file. -Force removes the protection, so treat it like -Confirm:$false.

Preview before you write: ConvertTo-Csv

ConvertTo-Csv produces the same CSV text but sends it to the pipeline instead of a file, which makes it ideal for checking your columns. In PowerShell 7 you can also drop the quotes when they are not needed (-UseQuotes is 7.0+ only):

Get-ChildItem -Path .\Logs -File |
    Select-Object -Property Name, Length |
    ConvertTo-Csv -UseQuotes AsNeeded
Enter fullscreen mode Exit fullscreen mode
Name,Length
app.log,26
error.log,15
report.txt,17
Enter fullscreen mode Exit fullscreen mode

PowerShell 7.4 vs Windows PowerShell 5.1 cheat sheet

Behavior PowerShell 7.4 Windows PowerShell 5.1
#TYPE line Off by default (-IncludeTypeInformation to add it) On by default (-NoTypeInformation to remove it)
Default encoding utf8NoBOM ASCII
UTF-8 with BOM for Excel -Encoding utf8BOM -Encoding UTF8
-UseQuotes, -QuoteFields, -NoHeader Available Not available
-Append, -Delimiter, -UseCulture, -NoClobber, -Force Available Available

Everything here is checked against the Microsoft Learn Export-Csv reference for both versions.

Practice it hands-on

Export pipelines stick faster when you build them yourself. If you want somewhere to experiment without touching real reports, you can practice PowerShell commands in a free browser terminal with CMD Master. It has interactive lessons for CMD, PowerShell and Bash.

Your turn: what's in the file?

No error is thrown. What does quiz.csv contain after this runs?

[pscustomobject]@{ Name = 'a.log'; Size = 10 } |
    Export-Csv -Path .\quiz.csv
[pscustomobject]@{ Name = 'b.log'; Size = 20; Owner = 'admin' } |
    Export-Csv -Path .\quiz.csv -Append

Get-Content -Path .\quiz.csv
Enter fullscreen mode Exit fullscreen mode

Post your answer in the comments before you run it, and say what happened to Owner. I'll reply with the real output and the rule behind it. If you'd rather test your guess first, run it in the CMD Master interactive PowerShell terminal.

Top comments (0)