Home > Software engineering >  CSV/Powershell Add an -Header
CSV/Powershell Add an -Header

Time:10-28

I have this loop :

foreach($line in Get-Content .\script2.csv)
{ $firstname = $line.split(';')[0] 
$lastname = $line.split(';')[1]
$email = $line.split(';')[2] 
$newLine = """$firstname"",""$lastname"",""$email"""
$newLine >> newCSV.csv }

I would like to add a specific header but I don't know where I should write "-header" in my little script.

Thanks

Edit :

I have a file like that :

A;B;C 
A;B;C 
A;B;C 
A;B;C 

And I need to have this :

"info1","info2","info3",...,"info18" 
"A","B",C","","","","","","","","","","","","","","",""
"A","B",C","","","","","","","","","","","","","","",""
"A","B",C","","","","","","","","","","","","","","",""
"A","B",C","","","","","","","","","","","","","","",""

CodePudding user response:

As I have commented, this can simply be done without loop:

Your input CSV (script2.csv)

A;B;C 
A;B;C 
A;B;C 
A;B;C 
# get objects from the input csv file and provide headers for the data
# then save this data with the default delimiter comma to a new file
Import-Csv -Path '.\script2.csv' -Delimiter ';'  -Header 'info1','info2','info3','info4','info5' | 
Export-Csv -Path '.\newCsv.csv' -NoTypeInformation

will give you a new file 'newCsv.csv' looking like this:

"info1","info2","info3","info4","info5"
"A","B","C",,
"A","B","C",,
"A","B","C",,
"A","B","C",,

If you need more fields as you have commented, you can simply create a string array to hod all the wanted headers and use that.

Something like

$header = 1..18 | ForEach-Object {"info$_"}
Import-Csv -Path '.\script2.csv' -Delimiter ';' -Header $header | 
Export-Csv -Path '.\newCsv.csv' -NoTypeInformation

This will save the newCsv.csv with this content:

"info1","info2","info3","info4","info5","info6","info7","info8","info9","info10","info11","info12","info13","info14","info15","info16","info17","info18"
"A","B","C",,,,,,,,,,,,,,,
"A","B","C",,,,,,,,,,,,,,,
"A","B","C",,,,,,,,,,,,,,,
"A","B","C",,,,,,,,,,,,,,,

ANY software reading such a file should be able to handle the empty fields, as there is absolutely no reason to fill these with "" to denote the field is empty.. Reading/Importing CSV should always return values as strings anyway, as Import-Csv does.


  • Import-Csv Creates table-like custom objects from the items in a delimiter-separated value file. Usually this delimiter is the comma, hence the extension Comma Separated Values (.csv)
  • Export-Csv Converts objects into a series of delimiter-separated value (CSV) strings and saves the strings to a file.
  • Get-Content Gets the content of a text file and returns a string array where the lines are split on the NewLine character(s).
    When adding switch -Raw to this cmdlet, it returns the content of the file as single multiline string including NewLine characters.
  • Related