Powershell has the Add-Content cmdlet to append data to the end of a file. While it also has Export-CSV cmdlet, that seems to be more for dealing with collections where you pipe a collection of objects directly to the CSV (Comma Separated Value) file. What if you have several variables and you want to put them in a CSV file, one row at a time?

In my application, I just needed to log the creation of a Video and it’s status (Success, Failure…) along with the current date/time, the keyword for that video, and the filename of the video. So I created a small 5 line function to the work, and then call it from different places in my application.

I simply create the $newRow, i.e. the row or line of text to be written to the CSV. I handle add the commas myself, to make it a proper CSV.

The advantage of a CSV file is of course that it can be opened with most any spreadsheet tool, such as Microsoft Excel.

function AddToCSV($filename,$result,$action,$keyword,$videoFilename){
    $showDate = get-date
    $newRow = "$showDate,$result,$action,$keyword,$text"
    Add-Content $filename $newRow
}

#Sample Test Logic

$myFileName = "c:\Users\neal.walters\Documents\test.csv"

AddToCSV $myFileName "Success" "CreatedVideo" "best appliances in Abilene TX" ""
AddToCSV $myFileName "Failure" "CreatedVideo" "best appliances in Irving TX" ""
AddToCSV $myFileName "Success" "CreatedVideo" "best appliances in Farmers Branch TX" ""
AddToCSV $myFileName "Success" "PostVideo" "best appliances in Farmers Branch TX" ""

If you have commas inside of your text fields, you would have to do a little more to do, i.e. surrounding each text field with quotes.

Below is a sample of data similar to the sample above.

Powershell_Variables_to_CSV_Viewed_In_Excel

Filed under: Powershell