簡體   English   中英

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

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

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

我也試過了

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

該文件似乎每次都被覆蓋。 有沒有辦法繼續向文件添加內容?

我收到錯誤

Export-Csv : A parameter cannot be found that matches parameter name 'Append'.

我不知道$filesremoved包含什么,但要在PS2.0中附加CSV輸出,你可以嘗試這樣的事情:

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

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"

在PowerShell 3.0之前, Export-Csv-Append參數不存在。

在PowerShell 2.0中解決此問題的一種方法是導入現有CSV,創建一些新行,附加兩個集合,然后再次導出。 例如,假設test.csv:

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

您可以使用如下腳本將一些行附加到此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

運行此腳本,test2.csv的內容將是:

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

一種可能性:

$CSVContent = $filesremoved | ConvertTo-Csv
$CSVContent[2..$CSVContent.count] | add-content E:\Code\powershell\logs\filesremoved.txt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM