2012-03-21 80 views
4

試圖找出如何將行添加到帶有標題的csv文件。 我得到使用內容:將行添加到powershell中的CSV文件

$fileContent = Import-csv $file -header "Date", "Description" 

$File回報

Date,Description 
Text1,text2 
text3,text4 

如何追加了新的日期和說明的行。對不起,我對PowerShell比較陌生。感謝任何可以幫助的人

+1

歡迎來到StackOverflow。在爲您的問題選擇標籤時請更加小心。我編輯你的問題更適合你的問題。 (標籤用於根據主題或主題將問題分類到不同的類別中,而您的「stackoverflow.com」原始標籤不僅不合適,而且與您的問題完全無關。)您可能還想訪問[FAQ] (http://stackoverflow.com/faq)來熟悉整個網站。 :) – 2012-03-21 21:38:22

回答

8

創建一個新的自定義對象並將其添加到Import-Csv創建的對象數組中。

$fileContent = Import-csv $file -header "Date", "Description" 
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' } 
$fileContent += $newRow 
+0

這對我很好,除了它改變了我的列的順序。在我使用上面的答案追加行後,我不得不使用'$ Import = $ Import | Select-Object ...'重新排序我的列以導出。 – mack 2014-03-21 18:46:51

9

要簡單地追加到PowerShell中的文件,您可以使用添加內容。

因此,爲了只添加一個新行到文件中,請嘗試以下操作,其中$ YourNewDate和$ YourDescription包含所需的值。

$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription 
$NewLine | add-content -path $file 

或者,

"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file 

這將只是標記的新線將.csv結束,並不會創造新的.csv文件,您將需要添加頁眉工作。

3

我知道這是一箇舊線程,但它是我在搜索時發現的第一個線程。 + =解決方案對我無效。我開始工作的代碼如下。

#this bit creates the CSV if it does not already exist 
$headers = "Name", "Primary Type" 
$psObject = New-Object psobject 
foreach($header in $headers) 
{ 
Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value "" 
} 
$psObject | Export-Csv $csvfile -NoTypeInformation 

#this bit appends a new row to the CSV file 
$bName = "My Name" 
$bPrimaryType = "My Primary Type" 
    $hash = @{ 
      "Name" = $bName 
      "Primary Type" = $bPrimaryType 
       } 

$newRow = New-Object PsObject -Property $hash 
Export-Csv $csvfile -inputobject $newrow -append -Force 

我能夠使用它作爲函數來循環訪問一系列數組並將內容輸入到CSV文件中。

它適用於PowerShell 3及以上版本。

+0

它工作完美。謝謝 :) – Sambhav 2015-07-08 05:23:09

相關問題