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

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

Which produces exactly what you would want to open in Excel:

"Name","SizeKB","LastWriteTime"
"server1.log","0.04","24/08/2026 14:00:59"
"server2.log","0.08","24/08/2026 14:00:59"

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.

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:

"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 *

Looking for SQL Server?

This site started as a SQL Server blog in 2017 and the archive is still here. The new SQL Server writing, and all the scripts, moved to a site of their own.

sqldba.blogScripts, error library, wait types, SSMS
Browse by topic