How to Export Data to CSV in PowerShell

📜Part of the PowerShell Complete Guide, every PowerShell post on this site, grouped by the job you are doing.
The short answer

Pipe anything into Export-Csv -Path report.csv -NoTypeInformation. On PowerShell 5.1 that switch is not optional if you want a usable file.

Almost every reporting job on Windows ends the same way: someone wants it in Excel. Export-Csv takes whatever objects PowerShell just produced and writes them out as columns.

The Basic Export

PowerShell
Get-ChildItem -Path "D:\Logs" -Recurse -File |
    Select-Object Name,
        @{Name = "SizeKB"; Expression = { [math]::Round($_.Length / 1KB, 2) }},
        LastWriteTime |
    Export-Csv -Path "C:\Reports\logs.csv" -NoTypeInformation -Encoding UTF8
Export-Csv writing D:\Logs file details to C:\Reports\logs.csv, then Get-Content showing the CSV, with the PowerShell 7 NoTypeInformation warning

The yellow warning in PowerShell 7 is the switch being flagged as obsolete there. It is harmless, and the line still works unchanged in Windows PowerShell 5.1.

Which produces exactly what you would want to open in Excel. Get-Content shows the raw file:

PowerShell exporting a file list to C:\Reports\logs.csv with Export-Csv, then Get-Content showing the header row and four quoted rows

The @{Name=...;Expression={...}} block is a calculated property. It is how you turn raw bytes into a readable megabyte column, or combine fields, without a loop.

Calculated properties are fiddly to type from memory. Tell Claude the columns the report needs and ask for the Select-Object line, then check the first few rows before the file goes to anyone.

Three Things Worth Knowing

1. -NoTypeInformation. Without it, Windows PowerShell 5.1 writes a #TYPE System.Management.Automation.PSCustomObject line at the top of the file, which breaks the header row in Excel. PowerShell 7 stopped doing this, so scripts that must run on both should keep the switch.

2. Appending. -Append adds rows to an existing file rather than replacing it, which is what you want for a scheduled script collecting daily numbers. The columns must match.

3. Encoding. Use -Encoding UTF8 if the data has any accented characters or symbols, otherwise Excel will make a mess of them.

The Gotcha That Got Me

Write the CSV somewhere outside the folder you are reporting on. Export it into the same directory you are scanning and, depending on order, the report can end up listing itself:

Text
"Name","SizeKB","LastWriteTime"
"report.csv","0","24/08/2026 14:01:10"     <-- the report, in its own report
"server1.log","0.04","24/08/2026 14:00:59"

Either write it elsewhere, or filter it out with Where-Object Name -ne 'report.csv' before the export.

Related


If SQL Server is part of your day job, my current work lives over at sqldba.blog: production DBA scripts, an error library and the SSMS guide.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *