我正在(很糟糕地)尝试将 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/