1

I have a csv file with only one column like below

Column1
Apple
Mango

I am try to append the csv to add more fruits by appending the current csv file with the following script

$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$csvPathforFruits = $path + "\Fruits.csv"
$importFruit = Import-Csv $csvPathforFruits
$new = "Orange"
$new |  Export-CSV $csvPathforFruits -Append

But following error is thrown out.

Export-CSV : Cannot append CSV content to the following file: C:\Users\sysadmin\Desktop\Test\Fruits.csv. The appended object does not have a property that corresponds to the following column: 
Colume1. To continue with mismatched properties, add the -Force parameter, and then retry the command.
At C:\Users\sysadmin\Desktop\Test\tt.ps1:5 char:9
+ $new |  Export-CSV $csvPathforFruits -Append
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (Colume1:String) [Export-Csv], InvalidOperationException
    + FullyQualifiedErrorId : CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell.Commands.ExportCsvCommand

Can anyone point out my mistakes.

2 Answers 2

2

A single column CSV is basically a text file with an entry on each line. This will do what you're after.

There is no need to import the CSV. I have set the encoding to utf8; if you run into problems try unicode

$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$csvPathforFruits = $path + "\Fruits.csv"

# In English: add a new line and then the word "Orange" to the bottom of the file.
"`nOrange" | Out-File $csvPathforFruits -Append -Encoding utf8
Sign up to request clarification or add additional context in comments.

Comments

1

When you import your CSV it is converted in to an object, you need to append a similar object but you are trying to append a string. Something like this would fix it:

$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$csvPathforFruits = $path + "\Fruits.csv"
$importFruit = Import-Csv $csvPathforFruits

$new = New-Object psobject -Property @{Column1 = "Orange"}
$new | Export-CSV $csvPathforFruits -Append 

Or even:

$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$csvPathforFruits = $path + "\Fruits.csv"
$importFruit = Import-Csv $csvPathforFruits

$importFruit += New-Object psobject -Property @{Column1 = "Orange"}
$importFruit | Export-CSV $csvPathforFruits -NoTypeInformation

But if your file is just one column of text then treating as a CSV seem to be overkill.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.