none
How to create an empty .csv file that contains only my header row?

    Question

  • Greetings.

    I'm writing a function to log activity from several scripts. Each entry includes a time stamp, message type (info,warning,error), and description. I use Out-File to write that data to the file, and it works fine, as long as it's writing to a valid .csv file.

    I need to do a pre-check and create the .csv file if it doesn't exist.

    As a work around, I did a query using get-item, select some non-existent parameters, and an export-csv. This creates the .csv with the headers which my logging function can write to without issue:

    Get-item c:\ -ea 0 | select Date,Type,Description -First 1 | export-csv $path -NoTypeInformation -force
    

    But this is messy, and certainly can't be the best way.

    I tried using

    $headers = @("Date","Type","Description") | export-csv $path -NoTypeInformation
    
    And that didn't work, either.

    but that results in a file with four rows of info in the first column

    Monday, January 23, 2012 3:30 PM

Answers

All replies

  • Try this trick:

    '' | select 'Date', 'Type', 'Description' | Export-Csv 'test.csv' -NoTypeInformation
    


    Grant Ward, a.k.a. Bigteddy

    What's new in Powershell 3.0 (Technet Wiki)

    Network Live Audit - Powershell script
    Monday, January 23, 2012 3:38 PM
  • "Date,Type,Description" | out-file test.csv
    Monday, January 23, 2012 3:44 PM
  • Wow - I was really over-thinking this. Thanks. That did the trick.
    Monday, January 23, 2012 3:57 PM
  • I tried this previously, but it doesn't work for me, as subsequent writes to the file all go in the first column, instead of separate columns.
    Monday, January 23, 2012 3:58 PM
  • this is great! nice work - I have a question, however; I get an error when trying to write duplicate values. 

    i.e. 

    '' | select '100', '0', 'welcome', 'UPDATE', 'EN', 'N', 'N' | Export-Csv 'test.csv'-NoTypeInformation

    apparently I can't have two columns with the same header. Thoughts?
    Sunday, June 21, 2015 3:44 AM
  • This whole thread is faulty.  Why would anyone use  CSV file as a log.  Just use Out-File and format the message.  The easiest way to do that is with a custom logging function.

    The thread is closed and has been for many years. Post any new uestions in aa new topic.


    \_(ツ)_/

    Sunday, June 21, 2015 4:43 AM
    Moderator
  • "This whole thread is faulty.  Why would anyone use CSV file as a log. "    Maybe he is trying to add to an existing workflow from the XP days?  Maybe the CSV file is used in another program, Query, or database.  Who are you to question why? 
    Thursday, March 15, 2018 4:43 PM