如何使用export-csv为PowerShell 2附加文件?

sof*_*fun 4 powershell powershell-2.0 export-to-csv

$filesremoved | export-csv -Path E:\Code\powershell\logs\filesremoved.txt -NoTypeInformation
Run Code Online (Sandbox Code Playgroud)

我也试过了

$filesremoved | export-csv -Path E:\Code\powershell\logs\filesremoved.txt -NoTypeInformation -NoClobber
Run Code Online (Sandbox Code Playgroud)

该文件似乎每次都被覆盖.有没有办法继续向文件添加内容?

我收到错误

Export-Csv : A parameter cannot be found that matches parameter name 'Append'.
Run Code Online (Sandbox Code Playgroud)

Fro*_* F. 8

我不知道$filesremoved包含什么,但要在PS2.0中附加CSV输出,你可以尝试这样的事情:

$filesremoved | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append -FilePath "test2.csv"
Run Code Online (Sandbox Code Playgroud)

Select-Object -Skip 1用于删除标题.但是,您应该指定所需的列顺序,分隔符和编码,例如:

$filesremoved | Select-Object -Property Name, Date | ConvertTo-Csv -Delimiter ";"  -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append -Encoding ascii -FilePath "test2.csv"
Run Code Online (Sandbox Code Playgroud)


Bil*_*art 6

在PowerShell 3.0之前,该-Append参数Export-Csv不存在.

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

"A","B","C"
"A1","B1","C1"
"A2","B2","C2"
Run Code Online (Sandbox Code Playgroud)

您可以使用如下脚本将一些行附加到此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
Run Code Online (Sandbox Code Playgroud)

运行此脚本,test2.csv的内容将是:

"A","B","C"
"A1","B1","C1"
"A2","B2","C2"
"A3","B3","C3"
"A4","B4","C4"
"A5","B5","C5"
Run Code Online (Sandbox Code Playgroud)