如何使用PowerShell 2的导出csv附加文件?

如何使用PowerShell 2的导出csv附加文件?,powershell,powershell-2.0,export-to-csv,Powershell,Powershell 2.0,Export To Csv,我也试过了 $filesremoved | export-csv -Path E:\Code\powershell\logs\filesremoved.txt -NoTypeInformation 文件似乎每次都被覆盖。是否有办法不断向文件中添加内容 我会犯错误 $filesremoved | export-csv -Path E:\Code\powershell\logs\filesremoved.txt -NoTypeInformation -NoClobber 在PowerShell

我也试过了

$filesremoved | export-csv -Path E:\Code\powershell\logs\filesremoved.txt -NoTypeInformation
文件似乎每次都被覆盖。是否有办法不断向文件中添加内容

我会犯错误

$filesremoved | export-csv -Path E:\Code\powershell\logs\filesremoved.txt -NoTypeInformation -NoClobber

在PowerShell 3.0之前,
导出Csv
-Append
参数不存在

在PowerShell 2.0中解决此问题的一种方法是导入现有CSV,创建一些新行,附加两个集合,然后再次导出。例如,假设test.csv:

Export-Csv : A parameter cannot be found that matches parameter name 'Append'.
您可以使用如下脚本将一些行附加到此CSV文件:

"A","B","C"
"A1","B1","C1"
"A2","B2","C2"
$CSVContent = $filesremoved | ConvertTo-Csv
$CSVContent[2..$CSVContent.count] | add-content E:\Code\powershell\logs\filesremoved.txt
运行此脚本,test2.csv的内容将是:

$rows = [Object[]] (Import-Csv "test.csv")
$addRows = 3..5 | ForEach-Object {
  New-Object PSObject -Property @{
    "A" = "A{0}" -f $_
    "B" = "B{0}" -f $_
    "C" = "C{0}" -f $_
  }
}
$rows + $addRows | Export-Csv "test2.csv" -NoTypeInformation
一种可能性:

"A","B","C"
"A1","B1","C1"
"A2","B2","C2"
"A3","B3","C3"
"A4","B4","C4"
"A5","B5","C5"

我不知道
$fileremoved
包含什么,但要在PS2.0中附加CSV输出,您可以尝试以下操作:

"A","B","C"
"A1","B1","C1"
"A2","B2","C2"
$CSVContent = $filesremoved | ConvertTo-Csv
$CSVContent[2..$CSVContent.count] | add-content E:\Code\powershell\logs\filesremoved.txt
选择对象-跳过1
用于删除标题。但是,您应该指定所需的列顺序、分隔符以及可能的编码,如:

$filesremoved | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append -FilePath "test2.csv"

对于那些正在寻找解决方案的人,请参阅我的文章“最佳解决方案”,因为它输出的数字范围在3到5之间。(在PowerShell提示符下输入
3..5
)我在上面的代码中使用它只是为了为CSV生成更多数据。我得到一个错误
不包含名为“op_Addition”的方法。
抱歉,我无法复制。我刚刚打开了一个PowerShell窗口,输入了
3..5
,它输出了三个数字(3、4和5)。对不起,我的意思是在代码的这一行
$rows+$addRows
@Bill\u Stewart如果文件包含零个或一个记录,
Import Csv
的结果不是大小为零或一的arry,而是单个对象。您需要将
$rows
声明到
[PsObject[]]$rows
以修复
操作添加
错误。