2

I'm looking for adding header to a csv file without header, and without information about columns number.

I have this code for csv file which I know column count :

    $Content = Import-Csv "C:\temp\input.csv" -Delimiter ';' -Header "1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23"

Which is the best way to create an header like mine, automatically ? Is "Header" parameter can be an arraylist of string value ?

I should code something like this :

$array = New-Object System.Collections.ArrayList
for ($i=1; $i -lt $Columns; $i++)
{
        $array.add($i.ToString())
} 
3
  • In fact, I wanted to create an header without hardcoding column value, in order to use it for any csv input file. see below my auto answer ;) Commented Feb 23, 2018 at 8:59
  • that's better, and easier than my way, thanks ;) Commented Feb 23, 2018 at 9:00
  • Great; for tidyness I've added it as an answer instead of a comment. Commented Feb 23, 2018 at 9:05

2 Answers 2

2

To make my comment into an answer:

The array construction operator .. makes an array of numbers, e.g. 1..5 is 1, 2, 3, 4, 5 and if you pass an array of numbers to -Header it will be turned into strings automatically, because of the way PowerShell types work - header is expecting a string array.

So you can create an array of however many numbers there are, like so:

-Header (1..$Columns)
Sign up to request clarification or add additional context in comments.

Comments

0

Ok, I've found my error :

$CSVFile = Get-Content $csvTemp
$Columns = ($CSVFile[0].split(";")).Count
[string[]]$tab = @()    
for ($i=1; $i -lt $Columns; $i++){
   $tab+= $i.ToString()
} 
$content = import-csv "c:\temp\test.csv" -delimiter ';' -header $tab

Comments

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.