Out-CSV Revised

A while ago I published a short function to create CSV strings. While working on another task I came across $OFS, which is something I know about but never really think about. $OFS is an intrinsic PowerShell variable that controls the output field separator for arrays. You can modify this variable which made me realize there was a better way to handle my Out-CSV function.  Here’s the revised function.

Function out-csv {
    Param([string]$property="Name",[string]$delimiter=",")
    
BEGIN { 
   #initialize placeholder array
    $csv=@()
}
PROCESS {
   #force each item to be a string and trim any spaces
   $item=($_.$property | out-string).Trim()
   #add item to the array
   $csv+=$item
   }
 
END {
    $OFS=$delimiter
    #send the comma separated string into the pipeline
    write ($csv -as [string])
 }
}

The function is designed so that it can take pipelined input. I’m assuming you want to create a CSV string from a collection of objects based on a single property. The function by default will look for the NAME property of any incoming object and if found, create a CSV separated list using a comma as the value for $OFS.

get-service | where {$_.status -eq “running”} | out-csv

But you can specify any property

get-eventlog -list | out-csv -property log

I like developing functions and scripts that are flexible. Even though 9/10 times you may want a CSV string, what if you need to create a string with a semi-colon as the delimiter? I don’t want to have to re-write the script so I added a parameter with a default value. If I want something different, it’s as easy as this:

Get-Process | where {$_.workingset -gt 10MB} | out-csv -delimiter “;”

I hope you’ll keep that in mind as you develop your own PowerShell solutions.

Download this new script here.