Reputation: 65
Is there a more efficient way to add headers to CSV file rather than hard-coding them?
$Importfile = Import-csv $path$filename -header H1, H2, H3, H4, H5, H6, H7 #add headers to csv file
Upvotes: 2
Views: 826
Reputation: 7479
here's one way to auto-generate a header line for a CSV file that does not have one. it counts the items in the 1st line of the file to generate the header row. [grin]
$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
output ...
Col_1 Col_2 Col_3 Col_4
----- ----- ----- -----
1001 Jon Smith Anvil Inspector
2002 Bob Archer Bow Builder
3003 Mike Carter Wagon Designer
Upvotes: 7