I have the following code:
$databaseContents = "col1,col2,col3,col4"
$theDatabaseFile = "C:\NewFolder\Database.csv
$databaseContents | Out-File $theDatabaseFile
However when I open the csv file in Excel, it has col1,col2,col3,col4 in cell A1 rather than col1 in cell A1, col2 in cell B1 etc.
Something strange I've noticed: If I open the file in Notepad and copy the text into another Notepad instance and save it as Database1.csv, then open it in Excel, it displays as expected.
How can I get the Out-File
commandlet to save it as a .csv file with the contents in 4 columns as expected?
EDIT:
I've noticed if I use Set-Content
rather than Out-File
, the csv file is then displayed correctly in Excel.
Does anyone know why this is?
The PowerShell Import-Csv cmdlet is an excellent way of reading data from a tabulated source such as a CSV file. You can use the ForEach loop to then iterate over each row in the CSV data. In this article, you'll learn how to use this powerhouse combination to automate bulk, mundane, and repetitive tasks.
To simply append to a file in powershell,you can use add-content. So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.
The Import-Csv cmdlet creates table-like custom objects from the items in CSV files. Each column in the CSV file becomes a property of the custom object and the items in rows become the property values. Import-Csv works on any CSV file, including files that are generated by the Export-Csv cmdlet.
Why it makes a difference to Excel I am unclear, but it comes down to the encoding of the resulting output file - Unicode (in the cases that do not work) vs. ASCII (in the cases that do).
@JPBlanc's alternate approach works because it sets the encoding of the output file to ASCII where your original example (implicitly) set the encoding of the output file to Unicode.
Just adding -Encoding ascii
to your original example works fine too:
$databaseContents = "col1,col2,col3,col4"
$theDatabaseFile = "C:\NewFolder\Database.csv
$databaseContents | Out-File $theDatabaseFile -Encoding ascii
And adding an explicit -Encoding unicode
to your original example yields the same broken result you encountered:
$databaseContents = "col1,col2,col3,col4"
$theDatabaseFile = "C:\NewFolder\Database.csv
$databaseContents | Out-File $theDatabaseFile -Encoding unicode
This is basically what was happening implicitly.
This works also :
$databaseContents = "col1;col2;col3;col4"
$theDatabaseFile = "C:\temp\Database.csv"
$databaseContents | Out-File $theDatabaseFile -Encoding ascii
By default CSV separator in Excel seams to be ';' and Out-File
save as unicode forcing ASCII
seams to give the result you look for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With