2014-01-10 110 views
4
$filesremoved | export-csv -Path E:\Code\powershell\logs\filesremoved.txt -NoTypeInformation 

我也試過如何使用適用於PowerShell 2的export-csv追加文件?

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

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

我得到的錯誤

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

http://stackoverflow.com/a/21047532/1035521 –

+0

對於那些誰正在尋找解決方案,請參閱我的文章http://stackoverflow.com/questions/38242541/alternative-to-append-export-csv-powershell/38243306#38243306 – DisplayName

+0

這個最佳解決方案 http://stackoverflow.com/questions/38242541/alternative-to-append -export-csv-powershell?noredirect = 1&lq = 1 – DisplayName

回答

6

Export-Csv-Append參數不存在,直到PowerShell的3.0。

在PowerShell 2.0中解決此問題的一種方法是導入現有CSV,創建一些新行,追加兩個集合,然後再次導出。例如,假設test.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" 

你可以使用這樣的腳本一些行追加到該CSV文件:

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

3..5是什麼意思? –

+0

它輸出範圍在3到5之間的數字(在PowerShell提示符下輸入'3..5'來查看它。)我在上面的代碼中使用它僅僅是爲了生成更多的CSV數據。 –

+0

我收到一個錯誤'不包含名爲'op_Addition'的方法。' –

0

一種可能性:

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

我不知道是什麼$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"