Eric Feurich
Eric Feurich

Reputation: 55

Powershell Add-Content doesn't add to end of file

I need to add a header to a csv file before importing it to a database. For some reason the header is added but the rest of the csv data isn't added on a newline but directly after it.

$file = Get-ChildItem \\some path to the datafile\IDM_dump | sort LastWriteTime | select -last 1
Copy-Item $file.FullName "D:\Program Files (x86)\Indocs\DatabaseImport\IDMdump.csv"

#Make copy of header info file because file will be renamed
Copy-Item 'D:\Program Files (x86)\Indocs\DatabaseImport\IDMheaderinfo.csv' 'D:\Program Files (x86)\Indocs\DatabaseImport\headerinfo.csv'

#Add header data at the first line of the data file
$valueDumpFile = Get-Content "D:\Program Files (x86)\Indocs\DatabaseImport\IDMdump.csv"

#Add-Content -Path 'D:\Program Files (x86)\Indocs\DatabaseImport\headerinfo.csv' -Value $valueDumpFile
Out-File -FilePath 'D:\Program Files (x86)\Indocs\DatabaseImport\headerinfo.csv' -InputObject $valueDumpFile -Append -NoClobber

#Rename file to new name
Rename-Item -Path 'D:\Program Files (x86)\Indocs\DatabaseImport\headerinfo.csv' -NewName IDMDumpWithHeader.csv

Upvotes: 1

Views: 489

Answers (2)

Robert Dyjas
Robert Dyjas

Reputation: 5227

If you still want to use Get-Content, check @James C.'s answer. In this answer I suggest different approach which might be more useful if you need to modify the data in the script, not only to join the files.


Wouldn't it be easier to use CSV-related cmdlets for it?

$object = Import-CSV .\data.csv -Header ((Get-Content .\headers.csv) -split ",")

Assuming the content of your files is as follows:

headers.csv

firstname,lastname,id

data.csv

john,doe,2
john,smith,1

The result will be the object:

PS C:\SO\51650194> $object = Import-CSV .\data.csv -Header ((Get-Content .\headers.csv) -split ",")
PS C:\SO\51650194> $object

firstname lastname id
--------- -------- --
john      doe      2
john      smith    1

You can then easily export it to .csv using Export-CSV.

Upvotes: 1

henrycarteruk
henrycarteruk

Reputation: 13227

As you're not using the data within Powershell, I would just treat the csv files as plain text and use Get-Content to join the files:

Get-Content $file1,$file2 | Set-Content $output_file

The order your specify the files is the order they are joined.

You don't need any copies of files or renaming, just join the files and output once to the desired name file:

$headers = 'D:\Program Files (x86)\Indocs\DatabaseImport\IDMheaderinfo.csv'
$output = 'D:\Program Files (x86)\Indocs\DatabaseImport\IDMDumpWithHeader.csv'

$file = Get-ChildItem \\server\IDM_dump | sort LastWriteTime | select -last 1

Get-Content $headers,$file.fullname | Set-Content $output

Upvotes: 1

Related Questions