Export Csv - PowerShell


Overview

Export-Csv is a robust PowerShell command that enables seamless data export from various objects, including objects created by cmdlets and scripts, into comma-separated value (CSV) files. This versatile tool finds extensive usage in data analysis, sorting, and transferring data between applications and systems.

Syntax

Export-Csv [-InputObject] <Object[]> [-Path] <String> [-Delimiter] <Char> [-Encoding] <Encoding> [-Force] [-NoTypeInformation] [-ExcludeTypeNames] [-UseCulture]

Options/Flags

  • -InputObject: Specifies the object(s) to be exported to the CSV file. Accepts an array of objects.

  • -Path: The destination path and file name for the CSV file. If not specified, defaults to the current directory and uses the default file name based on the input object’s type.

  • -Delimiter: Sets the delimiter character used in the CSV file. By default, this is a comma (‘,’).

  • -Encoding: Specifies the character encoding for the CSV file. Default is UTF8.

  • -Force: Overwrites the existing CSV file without prompting for confirmation.

  • -NoTypeInformation: Suppresses automatic inclusion of type information in the CSV file header.

  • -ExcludeTypeNames: Omits property type names from the CSV file header.

  • -UseCulture: Uses the current culture settings to format numerical and date values.

Examples

Basic Export:

Get-Process | Export-Csv -Path "C:\Temp\processes.csv"

Custom Delimiter and Encoding:

Get-ChildItem -Path C:\Temp | Export-Csv -Path "C:\Temp\files.csv" -Delimiter ";" -Encoding ASCII

Suppress Type Information:

Get-EventLog -LogName "System" | Export-Csv -Path "C:\Temp\events.csv" -NoTypeInformation

Common Issues

  • File Access Denied: Ensure you have write permissions to the destination directory.
  • Invalid Delimiter: The delimiter character must be a single character.
  • Incorrect Encoding: Verify that the specified encoding is supported by the system.

Integration

Export-Csv can be combined with other commands for advanced tasks:

  • Create a CSV from SQL Query:
Invoke-Sqlcmd -Query "SELECT * FROM Customers" | Export-Csv -Path "C:\Temp\customers.csv"
  • Filter and Export:
Get-Process | Where-Object {$_.ProcessName -like "explorer*"} | Export-Csv -Path "C:\Temp\explorer_processes.csv"
  • Import-Csv: Imports data from a CSV file into PowerShell objects.
  • Format-List: Formats objects in a tabular format.
  • Out-File: Exports objects to a text file.

Official Microsoft Documentation