Powershell how to add headers to a out-filed csv

644 views Asked by At

Do some of you know how to add headers to an out-file csv? I was looking on many other examples but don't find one that can help me.

Right now my output looks like this:

Name : Steve 
Adress: Berlin
Age: 21
And more....

but I would like to get it like this

Name  Adress   Age
----  -------  ---
Steve Berlin   21
[xml]$config = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Config.xml'
[xml]$blacklist = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Blacklist.xml'



#Names to filter
$BLN = $blacklist.Names
#Import Path
$info = Import-Csv $config.config.path.input -Delimiter ';'
$info | Format-Table
#from which month
#$dateCutoff = get-date "02.2020" -Format "MM.yyyy"
$dateCutoff = $config.config.date
$result = foreach($i in $info){
    if(-Not($BLN -contains $i.SCAN_USER)){


        $entryDate = Get-Date $i.SCAN_DATE -Format "MM.yyyy"


        if($entryDate -eq $dateCutoff){
        $i
        }
     }
   $result | Out-File $config.config.path.output 
   Write-Host $i
   $config.config.path.output + "\" + $info | Out-File -Append $config.config.path.output 
}
2

There are 2 answers

5
Nicicalu On BEST ANSWER

Using Export-CSV:

To export CSV documents you shouldn't use Out-File. You should use Export-CSV:

$data | Export-Csv -Path ".\yourdocumentname.csv" -NoTypeInformation -Delimiter ','

Using Out-File:

$data | ConvertTo-CSV -Delimiter ',' -NoTypeInformation | Out-File ".\yourdocumentname.csv" -Encoding utf8
2
Wasif On

Here you can't achieve luck using Import-Csv or Export-Csv if you are restricted to use out-file :(

What you have to do is you have to pass a pscustomobject to the output Csv file.

Give a try to this:

[pscustomobject]@{
  Name = "Anything, you can use variables in place of this string"
  Address = "String or variable"
  Age = Integer or Variable
} | out-file "filepath.csv"

Next when you want to get its content use get-content rather than import-Csv

Get-Content "filepath.csv"

If you are exporting hash tables to text file then first convert it to pscustomobject:

   $object = New-Object PSObject
   $hashtable.GetEnumerator() |  ForEach { Add-Member -inputObject $object -memberType NoteProperty -name $_.Name -value $_.Value }
  $object | out-file "filepath.csv"

FYI I have run test on TIO and my PC.