Home > Software design >  Export to CSV w/o Header or Quotes
Export to CSV w/o Header or Quotes

Time:01-15

I need to create a new CSV from an existing table, but I need to add a column before and have no headers, or quotes around the data within the cells. I noticed if I open the file, save it, quotes are removed but this file will be going external at 1AM nightly Example Example in Windows Explorer

$NewCSV = '\\server2\export.csv'
$Assets = (import-csv '\\server1\PCList.csv' | Where-Object {$_.PCNumber -ne ''}).PCnumber | ForEach-Object {

[pscustomobject]@{
'h1' = 'IT Support'
'h2' = $_ '.acme.net'
}

} | Export-Csv $NewCSV

I have seen usage of Outfile but that breaks my columns

CodePudding user response:

If you're running PowerShell (Core) 7 :

... | 
  ConvertTo-Csv -UseQuotes Never | 
    Select-Object -Skip 1 |
      Set-Content $NewCSV

If you're running Windows PowerShell:

... | 
  ConvertTo-Csv -NoTypeInformation | 
    Select-Object -Skip 1 |
      ForEach-Object { $_ -replace '"' } |
        Set-Content $NewCSV

Note:

  • ConvertTo-Csv is the in-memory equivalent of Export-Csv, which therefore allows skipping the first output object, representing the CSV header, via Select-Object.
    Set-Content can then be used to save the results to a file. Use its -Encoding parameter to control the character encoding.

    • In Windows PowerShell only, -NoTypeInformation is additionally needed to suppress the usually undesired type-annotation line that is emitted before the header line; the same goes for Export-Csv.
  • The following applies to both ConvertTo-Csv and Export-Csv:

    • In Windows PowerShell, all CSV column values are invariably double-quoted (enclosed in "..."), but in PowerShell (Core) 7 you can control the double-quoting behavior via the -UseQuotes parameter. Additionally, you can choose to selectively double-quote columns (fields), via the -QuoteFields parameter.
  •  Tags:  
  • Related