在powershell中将行添加到CSV文件

Ken*_*Ken 6 csv powershell

试图弄清楚如何将行添加到带有标题的csv文件中.我使用以下内容获取内容:

$fileContent = Import-csv $file -header "Date", "Description"
Run Code Online (Sandbox Code Playgroud)

$File 回报

Date,Description
Text1,text2 
text3,text4
Run Code Online (Sandbox Code Playgroud)

如何附加包含新日期和说明的行.对不起,我对PowerShell比较陌生.感谢任何可以提供帮助的人

And*_*ndi 12

创建一个新的自定义对象并将其添加到Import-Csv创建的对象数组中.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow
Run Code Online (Sandbox Code Playgroud)


小智 12

要简单地附加到PowerShell中的文件,您可以使用add-content.

因此,要仅向文件添加新行,请尝试以下操作:$ YourNewDate和$ YourDescription包含所需的值.

$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
Run Code Online (Sandbox Code Playgroud)

要么,

"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
Run Code Online (Sandbox Code Playgroud)

这只会将新行标记为.csv的末尾,并且无法创建新的.csv文件,您需要在其中添加标题.


cor*_*rky 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
Run Code Online (Sandbox Code Playgroud)

我能够将此功能用作遍历一系列数组并将内容输入CSV文件的功能。

它可以在Powershell 3及更高版本中使用。