【问题标题】:Dealing with duplicate headers in .csv files in Powershell在 Powershell 中处理 .csv 文件中的重复标题
【发布时间】:2013-09-17 22:12:44
【问题描述】:

我正在尝试使用 PS 脚本来尝试自动化流程的一部分,其中从一个部门系统的导出可以导入到另一个部门系统。我需要使用多个“;”分离的电子邮件地址并将它们分成单独的行,每行有 1 个地址,同时保留其余数据。我有一个主要工作的解决方案,它依赖于 Import-CSV。

我遇到的问题是我得到的导出有多行具有相同的列标题。这会导致 Powershell 给我错误“成员“结束”已经存在。” (其中“end”是多列的标题)。

当有重复的列标题时,这只是在运行“import-csv ./addresses.csv”时发生,所以我认为我正在运行 import-csv 命令本身,而不是我可能对脚本做的任何奇怪的事情.

编辑 csv 以更改其中一个列名可以解决此问题,但该要求使得该过程难以自动化。

powershell 有没有办法处理具有重复列名的 CSV?除了包含电子邮件地址的列名之外,我宁愿避免指定列名,因为它们似乎会定期更改。如果我可以保留他们正在使用的列名,那将是最好的。

【问题讨论】:

    标签: powershell csv


    【解决方案1】:

    我知道这是一篇旧帖子,但我认为其他人可能正在寻找“更好的解决方案”。

    我需要动态更正重复的标题。并且在我要导入的任何文件之前不知道字段会导致一些重大挑战。

    这是我所做的:

    # Use System.IO.StreamReader to get the first line. Much faster than Get-Content.
    $StreamReader = New-Object System.IO.StreamReader -Arg $csvTemp
    
    # Parse the first line with whatever delimiter you expect. Trim + Remove Empty columns.
    # Comment out the last part if you want to generate headers for those who are empty.
    [array]$Headers = $StreamReader.ReadLine() -Split "," | % { "$_".Trim() } | ? { $_ }
    
    # Close the StreamReader, as the file will stay locked.
    $StreamReader.Close()
    
    # For each Header column
    For ($i=0; $i -lt $Headers.Count; $i++) {
    
        if ($i -eq 0) { Continue } #Skip first column.
    
        # If in any previous column, give it a generic header name
        if ($Headers[0..($i-1)] -contains $Headers[$i]) {
            $Headers[$i] = "Header$i"
        }
    }
    
    # Import CSV with the new headers 
    Import-Csv $csvTemp -Header $Headers
    

    【讨论】:

      【解决方案2】:

      如果您提前知道列数据将是什么,那么只需指定您自己的标题名称,这将忽略文件中的标题行。

      Import-CSV -Header header1, header2, header3 addresses.csv
      

      【讨论】:

      • 这不会给我留下一个与输入文件具有不同标题的输出文件吗?如果可能的话,我希望保持标题完好无损。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 2011-09-05
      • 2021-12-01
      相关资源
      最近更新 更多