2

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

1
  • 3
    you can use Get-Content to load the 1st line of a file, split by the delimiter, count the items, and then use that to generate the header row. Commented Aug 15, 2019 at 1:41

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

2 Comments

That's great. Thanks!
@Alex - you are most welcome! glad to help a tad now & then ... [grin]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.