【问题标题】:Read an .csv and export it to a brand new csv file - PowerShell读取 .csv 并将其导出到全新的 csv 文件 - PowerShell
【发布时间】:2014-01-08 23:07:08
【问题描述】:

我是使用 powershell 的新手,需要一些帮助。我有一个名为 test.csv 的 csv,看起来像这样:

----------------------------------
name         lastname       alias        
John         Smith          John              
Marie        Curie          Mary
----------------------------------

问题是我需要将两行的信息导出到两个不同的文件中。文件名应该是“别名”列下的那个

例子:

Name: John

-----------------------------------
name         lastname       alias        
John         Smith          John

-----------------------------------

Mary

----------------------------------
name         lastname       alias        
Marie        Curie          Mary

----------------------------------

我尝试了以下脚本:

Import-Csv c:\test\test.csv  | foreach ($line ){New-Item c:\test\$_alias.csv -type file}

有什么建议吗?

【问题讨论】:

    标签: powershell csv


    【解决方案1】:

    这个脚本应该适合你。它为每一行创建一个新文件,使用alias 字段作为文件名。

    $Data = Import-Csv -Path c:\test\test.csv;
    
    foreach ($Item in $Data) {
        Export-Csv -InputObject $Item -NoTypeInformation -Path ('c:\test\{0}.csv' -f $Item.Alias);
    }
    

    【讨论】:

      【解决方案2】:

      我的解决方案使用脚本循环和变量:

      $path = "c:\test\"
      $csv = Import-Csv "$($path)test.csv"
      $csv |
      %{
          Export-Csv -InputObject $_ -NoTypeInformation -Path "$($path)$($_.Alias).csv"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-14
        • 2023-03-27
        • 2021-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多