Merging and appending to CSV files using Powershell

The time-tested approach of appending data to the end of a file using >> doesn’t necessarily work with CSV files in Powershell, and Out-File with the -append switch typically results in a corrupted CSV file.

Recently I wrote a Powershell script for a customer to poll GPO information on a periodic basis and write that information to a CSV logfile for troubleshooting purposes.

The following worked for me, for what it’s worth :


# check for the Quest ActiveRoles Powershell module

if(-not(get-pssnapin -name Quest.ActiveRoles.ADManagement -ea:silentlycontinue)){add-pssnapin Quest.ActiveRoles.ADManagement}

# check for the GroupPolicy Powershell module

if(-not(get-module -name GroupPolicy -ea:silentlycontinue)){import-module grouppolicy}

$csvfile =‘c:\GPO_Diag_Report.csv’

# Get a list of all the root level domain GPOs and their link status, write to the CSVFILE

(Get-GPInheritance -target “dc=contoso,dc=com”).gpolinks | Select DisplayName, Enabled, Enforced, Target | export-csv $csvfile -notype

# Get a list of all GPOs by OU, pipe the resulting output as CSV formatted into a variable called CSVLines

get-qadobject -type organizationalunit -sizelimit 0 -DontUseDefaultIncludedProperties | foreach {(get-gpinheritance -target $_).gpolinks} | select DisplayName,Enabled,Enforced, Target | sort Enabled | ConvertTo-csv -outvariable CSVLines -notype

# Iterate thru each element in the CSVLines array and write the value to the CSVFILE using add-content

$CSVLines[1..($CSVLines.count 1)] | foreach-object {add-content -value $_ -path $csvfile}


There are undoubtedly other ways to achieve the same result, however this has worked reliably for me with no file corruption.

Comments (0)

Skip to main content