试图弄清楚如何向带有标题的csv文件添加行。 我使用以下内容获取内容:
$fileContent = Import-csv $file -header "Date", "Description"
$File
返回
Date,Description
Text1,text2
text3,text4
如何附加包含新日期和说明的行。对不起,我对PowerShell比较陌生。感谢任何可以提供帮助的人
答案 0 :(得分:11)
创建一个新的自定义对象并将其添加到Import-Csv
创建的对象数组中。
$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow
答案 1 :(得分:11)
要简单地附加到PowerShell中的文件,您可以使用add-content。
因此,要仅向文件添加新行,请尝试以下操作:$ YourNewDate和$ YourDescription包含所需的值。
$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
或者,
"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
这只会将新行标记为.csv的末尾,并且无法创建新的.csv文件,您需要添加标题。
答案 2 :(得分:5)
我知道这是一个旧帖子,但这是我在搜索时找到的第一个。 + =解决方案对我不起作用。我开始工作的代码如下所示。
#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及以上版本。
答案 3 :(得分:0)
对我来说很简单,就像这样:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables
如果您有很多列,请创建一个像$NewRow
这样的变量:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).
$NewRow | Add-Content -Path $File # Keep no space between content variables
请注意文件的Set-Content
(覆盖现有内容)和Add-Content
(附加到现有内容)之间的区别。