[powershell] Add rows to CSV File in powershell

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

This question is related to powershell csv

The answer is


Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.


I know this is an old thread but it was the first I found when searching. The += solution did not work for me. The code that I did get to work is as below.

#this bit creates the CSV if it does not already exist
$headers = "Name", "Primary Type"
$psObject = New-Object psobject
foreach($header in $headers)
{
 Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
}
$psObject | Export-Csv $csvfile -NoTypeInformation

#this bit appends a new row to the CSV file
$bName = "My Name"
$bPrimaryType = "My Primary Type"
    $hash = @{
             "Name" =  $bName
             "Primary Type" = $bPrimaryType
              }

$newRow = New-Object PsObject -Property $hash
Export-Csv $csvfile -inputobject $newrow -append -Force

I was able to use this as a function to loop through a series of arrays and enter the contents into the CSV file.

It works in powershell 3 and above.


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

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.