【问题标题】:Add rows to CSV File in powershell在PowerShell中将行添加到CSV文件
【发布时间】:2012-04-06 11:31:11
【问题描述】:

试图弄清楚如何在带有标题的 csv 文件中添加一行。 我使用以下方式获取内容:

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

$File 返回

Date,Description
Text1,text2 
text3,text4

如何在行中添加新的日期和说明。抱歉,我对 powershell 比较陌生。感谢任何可以提供帮助的人

【问题讨论】:

  • 欢迎来到 StackOverflow。请在为您的问题选择标签时更加小心。我编辑了你的更适合你的问题。 (标签用于按主题或主题将问题分组,您原来的标签stackoverflow.com 不仅不合适,而且与您的问题完全无关。)您可能还想访问FAQ 以熟悉自己与网站一般。 :)

标签: powershell csv


【解决方案1】:

要简单地附加到 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 文件。

【讨论】:

  • 谢谢你marceljg。我一直在寻找相同的解决方案,而你的一个班轮非常适合我。
  • 只是想知道有没有一种简单的方法来预先添加添加的行而不是追加?
【解决方案2】:

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

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

【讨论】:

  • 这对我很有用,只是它改变了我的列的顺序。在我使用上述答案添加该行之后,我不得不使用$Import = $Import | Select-Object... 重新排序我的列以进行导出。
【解决方案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 及更高版本。

【讨论】:

    【解决方案4】:

    对我来说简单是这样的:

    $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(附加到现有内容)之间的区别。

    【讨论】:

      【解决方案5】:

      我发现使用$newRowToAdd | Export-Csv -Append 是最简单的方法。不确定是哪个版本引入的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 2022-01-23
        • 1970-01-01
        相关资源
        最近更新 更多