ConvertTo CSV - PowerShell


Overview

ConvertTo-CSV converts objects from a data source into a comma-separated value (CSV) text file. It’s commonly used to export data from PowerShell objects or other data structures into a format compatible with other applications, such as spreadsheets or databases.

Syntax

ConvertTo-CSV [-InputObject] <Object> [-Delimiter <String>] [-NoTypeInformation] [-Encoding <Encoding>] [-Append] [-Force]
[[-File] <String>]

Options/Flags

  • -InputObject : Specifies the input object or data source to be converted to CSV. Accepts objects, arrays, or collections of objects.
  • -Delimiter : Sets the delimiter character used to separate values in the CSV file. Default: ,
  • -NoTypeInformation: Omits type information headers from the CSV file. By default, type information is included.
  • -Encoding : Specifies the character encoding to use when saving the CSV file. Default: Unicode (UTF-8)
  • -Append: Appends the new CSV data to an existing CSV file instead of overwriting it.
  • -Force: Overwrites an existing CSV file without confirmation.
  • -File : Specifies the path and filename of the CSV file to create or append to.

Examples

Export Objects to CSV:

Get-Process | ConvertTo-CSV -Path "process.csv"

Customize Delimiter:

Get-ChildItem | ConvertTo-CSV -Delimiter "|" -Path "files.csv"

Export with Type Information Headers:

Get-Service | ConvertTo-CSV -InputObject -Path "services.csv"

Common Issues

  • Invalid Delimiter: Ensure the delimiter specified is a valid character. Using invalid characters may result in malformed CSV data.
  • File Not Overwritten: If -Force is not specified, the command will not overwrite existing CSV files. Use -Force to avoid this.

Integration

Combine with Export-Csv:

Get-EventLog -LogName System | Export-Csv -Path "events.csv" | ConvertTo-CSV -Delimiter ";"

Filter and Export:

Get-Process | Where {$_.ProcessName -like "powershell*"} | ConvertTo-CSV -Path "powershell_processes.csv"
  • Export-Csv: Exports objects directly to a CSV file without converting to text.
  • Select-Object: Selects specific properties from objects for inclusion in the CSV file.
  • ForEach-Object: Iterates over objects and applies ConvertTo-CSV to each one.