2017-05-25 92 views
0

我有只有一列像下面PowerShell的追加CSV错误

Column1 
Apple 
Mango 

我尝试追加CSV用下面的脚本

$path  = Split-Path -parent $MyInvocation.MyCommand.Definition 
$csvPathforFruits = $path + "\Fruits.csv" 
$importFruit = Import-Csv $csvPathforFruits 
$new = "Orange" 
$new | Export-CSV $csvPathforFruits -Append 
附加当前的CSV文件中添加更多的水果csv文件

但是下面的错误被抛出。

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 

任何人都可以指出我的错误。

回答

2

单列CSV基本上是一个文本文件,每行都有一个条目。这将做你以后的事情。

无需导入CSV。我已将编码设置为utf8;如果您遇到问题,请尝试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 
1

当您导入CSV它转换到一个对象,你需要添加一个类似的对象,但你想追加一个字符串。这样的事情会解决它:

$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 

甚至:

$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 

但是如果你的文件只是那么文本处理为CSV一列似乎是大材小用。