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-Csvis the in-memory equivalent ofExport-Csv, which therefore allows skipping the first output object, representing the CSV header, viaSelect-Object.
Set-Contentcan then be used to save the results to a file. Use its-Encodingparameter to control the character encoding.- In Windows PowerShell only,
-NoTypeInformationis additionally needed to suppress the usually undesired type-annotation line that is emitted before the header line; the same goes forExport-Csv.
- In Windows PowerShell only,
The following applies to both
ConvertTo-CsvandExport-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-UseQuotesparameter. Additionally, you can choose to selectively double-quote columns (fields), via the-QuoteFieldsparameter.
- In Windows PowerShell, all CSV column values are invariably double-quoted (enclosed in
