Powershell - 合并 CSV 文件并附加一列

标签 powershell

我正在(很糟糕地)尝试将 CSV 文件合并到一个文件中,并在前面添加一个包含文件名的列。我是 PowerShell 的新手,希望有人能在这里提供帮助。

我最初尝试使用 Import-Csv/Export-Csv 的有据可查的方法,但我没有看到任何添加列的选项。

Get-ChildItem -Filter *.csv | Select-Object -ExpandProperty FullName | Import-Csv | Export-Csv CombinedFile.txt -UseQuotes Never -NoTypeInformation -Append

接下来,我尝试遍历文件并附加名称,这种方法可行,但由于某种原因,它在生成第一行后停止。由于它不是 CSV 过程,我必须使用开关跳过每个文件的第一个标题行。

$getFirstLine = $true

Get-ChildItem -Filter *.csv | Where-Object {$_.Name -NotMatch "Combined.csv"} | foreach {
    $filePath = $_

$collection = Get-Content $filePath  
    foreach($lines in $collection) {
        $lines = ($_.Basename + ";" + $lines)
    }

    $linesToWrite = switch($getFirstLine) {
           $true  {$lines}
           $false {$lines | Select -Skip 1}

    }
    
    $getFirstLine = $false
    Add-Content "Combined.csv" $linesToWrite
}

最佳答案

这就是 -PipelineVariable 参数派上用场的地方。您可以设置一个变量来表示管道中的当前迭代,这样您就可以执行以下操作:

Get-ChildItem -Filter *.csv -PipelineVariable File | Where-Object {$_.Name -NotMatch "Combined.csv"} | ForEach-Object { Import-Csv $File.FullName } | Select *,@{l='OriginalFile';e={$File.Name}} | Export-Csv Combined.csv -Notypeinfo

关于Powershell - 合并 CSV 文件并附加一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71315530/

相关文章:

xml - Powershell 添加内容截断输出

git - 我安装了 Github Desktop,是否需要安装 Git 才能使用命令行?

powershell - 从多个文件创建powershell模块,引用模块

powershell - 尝试使用 Invoke-SQLCmd 和 -ErrorAction SilentlyContinue Catch

powershell - 删除父路径

azure - 如何使用 PowerShell 跨 Azure 订阅列出资源组?

powershell - 直到用户输入是/否

powershell - IF 语句中的动态条件参数?

没有标题行的 Powershell Export-Csv

azure - PowerShell 版本及其管理 Azure Active Directory 的能力有何区别?