How to append data into a CSV file using PowerShell?



To append the data into CSV file you need to use –Append parameter while exporting to the CSV file.

In the below example, we have created a CSV file

Example

$outfile = "C:\temp\Outfile.csv" $newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile $csvfile = Import-Csv $outfile $csvfile.Emp_Name = "Charles" $csvfile.EMP_ID = "2000" $csvfile.CITY = "New York" $csvfile | Export-CSV $outfile Import-Csv $outfile

Now we need to append the below data to the existing file. So first we will import the csv file into a variable called $csvfile

$csvfile = Import-Csv $outfile $csvfile.Emp_Name = "James" $csvfile.EMP_ID = "2500" $csvfile.CITY = "Scotland"

Once data is inserted into a variable, we will append data with Append parameter.

$csvfile | Export-CSV $outfile –Append

Check the output:

Import-Csv $outfile

Output

EMP_Name    EMP_ID     CITY --------    ------     ---- Charles     2000       New York James       2500       Scotland
Updated on: 2020-03-26T07:28:05+05:30

43K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements