Add a row to an existing CSV

I am working on a script to capture key bits of server information from a large list of servers. With each server, I'd like to graph trending data from each server (drive usage, memory usage, etc.). With this I need a place to store the data after each run of the script, opting for storing the output into a CSV file (especially considering the ease of use of the Import/export csv functions in powerhsell).

My dilemna. Powershell's Export-csv does not have an append option. If you write to the file, it will always overwrite. Ugh. I could use the out-file cmd-let, but that requires defining the structure of my data to be output each and every time.

What I found was that I could do op_addition to a CSV file record if it contains 2 or more data records.

Name, IP
A, 192.168.1.1
B, 192.168.1.2

So, I've modified my script to put out 2 copies of the data, if the CSV does not exist; like below:

# $server is a record containing the Name, IP, etc.
$csvFile = "c:\serverList.csv"
if (Test-Path $csvFile) {
#CSV file is found
   $ExistingData = Import-Csv $csvFile
# this line appends the data to the end of $ExistingData
   $ExistingData += $Server
   $ExistingData  | export-csv -Path $csvFile
} else {  
#file does not exist
   $Servers=@()
   $servers += $server
#### add duplicate record to CSV
####  not single record on second read
   $servers += $server  
   $Servers | export-csv -Path $csvFile
}

Now, I'll have to code around not using the first line of the CSV, but that sounds easier than coding the entire out-file cmdlet.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <blockquote> <center> <hr> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <drupal6>, <html>, <java>, <javascript>, <php>, <posh>.

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.