我正在嘗試(非常糟糕)將 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
}
uj5u.com熱心網友回復:
這是-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
uj5u.com熱心網友回復:
將您的 CSV 合并為一個并為檔案名添加一列可以如下完成,使用上的計算屬性Select-Object:
Get-ChildItem -Filter *.csv | ForEach-Object {
$fileName = $_.Name
Import-Csv $_.FullName | Select-Object @{
Name = 'FileName'
Expression = { $fileName }
}, *
} | Export-Csv path/to/merged.csv -NoTypeInformation
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435590.html
標籤:电源外壳
