I’m currently trying to figure out how to get PowerShell to create a new CSV file, and append information to the CSV file it creates. I’m doing this on a test script right now just to try and figure out the functionality, but I’m stuck. Here’s what I have currently (For privacy, full file path is reduced to “File Path”):
Clear-Host
$CSVLog = New-Item "\File PathLogs$(Get-Date -f yyyy-MM-dd_hh-mm-ss) Test Log.csv" -ItemType File -Force
$i = 0
[PSCustomObject]@{
'Column1' = ''
'Column2' = ''
'Column3' = ''
}
DO
{
$i++
$CSVLog.add(
[PSCustomObject]@{
'Column 1' = 'Test'
'Column 2' = 'Super Test'
'Column 3' = $i
} ) |
Export-Csv "\File PathLogs$(Get-Date -f yyyy-MM-dd_hh-mm-ss) Test Log.csv" -NoTypeInformation -Append
} While ($i -lt 5)
Currently, PowerShell just spits out a blank CSV file at the specified location, and will put this in the host window:
Column1 Column2 Column3
------- ------- -------
PS C:WINDOWSsystem32>
What do I need to change here in order to make this work as intended?
Edit (in response to comment):
If you know the names of your columns, just create an empty csv by outputting a single line of the comma separated column names:
'"Column 1","Column 2","Column 3"' > test.csv
Then you can add to it using append:
[PSCustomObject]@{
>> 'Column 1' = 'Test'
>> 'Column 2' = 'Super Test'
>> 'Column 3' = 1
>> } | export-csv -path test.csv -NoTypeInformation -append
Original answer:
You don’t need to append each item one at a time, just output the objects onto the pipeline into Export-Csv
and it will take care of appending for you:
1..5 | %{[PSCustomObject]@{
'Column 1' = 'Test'
'Column 2' = 'Super Test'
'Column 3' = $_
} } | export-csv -path test.csv -NoTypeInformation
once you’ve added some initial values, you can use -append
to add more:
6..9 | %{[PSCustomObject]@{
'Column 1' = 'Test'
'Column 2' = 'Super Test'
'Column 3' = $_
} } | export-csv -path test.csv -NoTypeInformation -Append
or
2