Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add rows to CSV File in powershell

Tags:

powershell

csv

Trying to figure out how to add a row to a csv file with titles. I get the content using:

$fileContent = Import-csv $file -header "Date", "Description"

$File returns

Date,Description
Text1,text2 
text3,text4

How do I append a row with a new date and description. Sorry I am relatively new to powershell. thanks to anyone that can help

like image 930
Ken Avatar asked Mar 21 '12 21:03

Ken


2 Answers

To simply append to a file in powershell,you can use add-content.

So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.

$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file

Or,

"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file

This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.

like image 180
marceljg Avatar answered Oct 21 '22 11:10

marceljg


Create a new custom object and add it to the object array that Import-Csv creates.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow
like image 39
Andy Arismendi Avatar answered Oct 21 '22 12:10

Andy Arismendi