MISC.‎ > ‎

Out-CSV (Powershell)

Here is a nice and useful function I wrote.

It Can out put almost any object to a CSV file, the nice thing it can Append to it as well.

You can call it using pipeline or inputObject, the function will recognize the object properties and use them as the headers of the CSV, you can also enter your own header name (only to string objects).

Download The Script


# ==========================================================

# Out-CSV.ps1

# Made By : Assaf Miron

# http://assaf.miron.googlepages.com

# Description : Outputs and appends an object to a CSV File

# ==========================================================

function out-CSV ( $LogFile, $Append = $false) {

# Input : An Object with values, Boolean value if to append the file or not, a File path to a Log File

# Output : Export of the object values to a CSV File

# Description : This Function Exports all the Values and Headers of an object to a CSV File.

#  The Object is recieved with the Input Const (Used with Pipelineing) or the $inputObject

Foreach ($item in $input){

# Get all the Object Properties

$Properties = $item.PsObject.get_properties()

# Create Empty Strings - Start Fresh

$Headers = ""

$Values = ""

# Go over each Property and get it's Name and value

$Properties | %{ 

$Headers += $_.Name+"`t"

$Values += $_.Value+"`t"


# Output the Object Values and Headers to the Log file

If($Append -and (Test-Path $LogFile)) {

$Values | Out-File -Append -FilePath $LogFile -Encoding Unicode


else {

# Used to mark it as an Powershell Custum object - you can Import it later and use it

# "#TYPE System.Management.Automation.PSCustomObject" | Out-File -FilePath $LogFile

$Headers | Out-File -FilePath $LogFile -Encoding Unicode

$Values | Out-File -Append -FilePath $LogFile -Encoding Unicode