freud44
freud44

Reputation: 21

Powershell - Add header during input-csv command

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())
} 

Upvotes: 2

Views: 422

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

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)

Upvotes: 2

freud44
freud44

Reputation: 21

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

Upvotes: 0

Related Questions