是否有更有效的方法将标头添加到CSV文件,而不是对其进行硬编码?
$Importfile = Import-csv $path$filename -header H1, H2, H3, H4, H5, H6, H7 #add headers to csv file
答案 0 :(得分:6)
这是一种自动为没有一个CSV文件生成标题行的方法。它计算文件第一行中的项目以生成标题行。 [咧嘴]
$FileName = "$env:TEMP\Alex_-_Headerless.csv"
$Delimiter = ','
#region >>> create a headerless CSV file to work with
# remove this section when you are ready to do stuff for real
$HeaderlessCSV = @'
1001, Jon, Smith, Anvil Inspector
2002, Bob, Archer, Bow Builder
3003, Mike, Carter, Wagon Designer
'@ | Set-Content -LiteralPath $FileName
#endregion >>> create a headerless CSV file to work with
$ColumnCount = @((Get-Content -LiteralPath $FileName -TotalCount 1).Split($Delimiter)).Count
$HeaderLine = foreach ($Index in 1..$ColumnCount)
{
'Col_{0}' -f $Index
}
$InStuff = Import-Csv -Delimiter $Delimiter -Header $HeaderLine -LiteralPath $FileName
$InStuff
输出...
Col_1 Col_2 Col_3 Col_4
----- ----- ----- -----
1001 Jon Smith Anvil Inspector
2002 Bob Archer Bow Builder
3003 Mike Carter Wagon Designer