Powershell附加CSV错误

时间:2017-05-25 12:51:11

标签: powershell powershell-v4.0

我有一个只有一列的csv文件,如下所示

Column1
Apple
Mango

我尝试通过使用以下脚本附加当前csv文件来附加csv以添加更多水果

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

但是抛出了以下错误。

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 个答案:

答案 0 :(得分: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 :(得分: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似乎有点矫枉过正。