How can I append files using export-csv for PowerShell 2?

最后都变了- 提交于 2019-12-05 12:42:39

The -Append parameter of Export-Csv doesn't exist until PowerShell 3.0.

One way to work around it in PowerShell 2.0 is to import the existing CSV, create some new rows, append the two collections, and export again. For example, suppose test.csv:

"A","B","C"
"A1","B1","C1"
"A2","B2","C2"

You could append some rows to this CSV file using a script like this:

$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

Run this script and the content of test2.csv will be:

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

I have no idea what $filesremoved include, but to append CSV-output in PS2.0, you could try somthing like this:

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

Select-Object -Skip 1 is used to remove the header. You should however specify the columns-order you need, the delimiter and maybe encoding, like:

$filesremoved | Select-Object -Property Name, Date | ConvertTo-Csv -Delimiter ";"  -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append -Encoding ascii -FilePath "test2.csv"

One possibility:

$CSVContent = $filesremoved | ConvertTo-Csv
$CSVContent[2..$CSVContent.count] | add-content E:\Code\powershell\logs\filesremoved.txt
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!