How to Export PSCustomObject to CSV in PowerShell

Problem

In PowerShell, CSV (Comma-Separated Values) is a widely used file format for storing tabular data. By exporting PSCustomObject to CSV, you can save the data in a human-readable and interoperable format, making it easy to share, transfer, or persist the data across different systems and applications.

In this blog post, we will show you many ways to export PSCustomObject to CSV in PowerShell.

Using Export-Csv Cmdlet

To export a PSCustomObject to a CSV file in PowerShell, first we create a PSCustomObject with the desired properties and values. Then, we use Export-Csv cmdlet to export the object to a CSV file along with the file path where you want to save the CSV file.


$myObject = [PSCustomObject]@{
    Name = "John Doe"
    Age  = 30
    City = "San Francisco"
}

$myObject | Export-Csv -Path "C:\Scripts\output.csv" -NoTypeInformation

The -NoTypeInformation parameter ensures that CSV file does not contain .NET type information as the first line.

After running these commands, PSCustomObject will be exported to a CSV file at the specified path. Each property of the object will be represented as a column in the CSV file, and the values will be stored accordingly.

As a note, if the CSV file already exists, using Export-Csv with the same file path will overwrite the existing file. If you want to append PSCustomObject to an existing CSV file, you can use the ConvertTo-Csv cmdlet in combination with Out-File or Add-Content.

The result will look as follows:

Result of Using Export-Csv Cmdlet

Using ConvertTo-Csv Cmdlet

We can also use ConvertTo-Csv cmdlet combined with Set-Content to export PSCustomObject to a CSV file.


$myObject = [PSCustomObject]@{
    Name = "John Doe"
    Age  = 30
    City = "San Francisco"
}

$csvData = $myObject | ConvertTo-Csv -NoTypeInformation
$csvData | Set-Content -Path "C:\Scripts\output.csv"

In this approach, ConvertTo-Csv cmdlet is used to convert PSCustomObject to CSV format, and then the resulting CSV data is written to a file using Set-Content. The -NoTypeInformation parameter prevents the inclusion of .NET type information in the CSV file.

The result will look as follows:

Result of Using ConvertTo-Csv Cmdlet

Exclude the Header from the Output

To exclude the header line from the output, we can modify script in previous approach by utilizing Select-Object and Skip parameter.


$myObject = [PSCustomObject]@{
    Name = "John Doe"
    Age  = 30
    City = "San Francisco"
}

$csvData = $myObject | ConvertTo-Csv -NoTypeInformation
$csvData | Select-Object -Skip 1 | Set-Content -Path "C:\Scripts\output.csv"

The result will look as follows:

Exclude the Header from the Output

Conclusion

To export PSCustomObject to CSV in PowerShell, we can use some cmdlets like Export-Csv and ConvertTo-Csv. On the other hand, if we want to exclude the header from CSV output, we can utilize Select-Object and Skip parameter.