Functions/Get-CombinedCsvString.ps1
<#
.SYNOPSIS This function returns the result of combining CSVs. .DESCRIPTION This function returns the result of combining CSVs. The resulting CSV contains all the columns which were present in any of original CSVs. The combined CSV will contain the columns in sorted order. #> function Get-CombinedCsvString { [CmdletBinding()] [OutputType([String])] param ( [Parameter(Mandatory=$true)] [ValidateNotNull()] [String[]]$csvStrings ) # Validate the CSV strings foreach ($csvString in $csvStrings) { if ([String]::IsNullOrWhiteSpace($csvString)) { Write-Error "One or more of the CSV strings to combine is null/whitespace." return $null } } # Remove the sep=, from the beginning if present $csvStrings = $csvStrings | ForEach-Object -Process { if ($_ -like "sep=,*") { [Regex]::new("sep=,[\s]+([\s\S]*)").Match($_).Groups[1].Value } else { $_ } } # Collate all the column names $columnNames = @{} foreach ($csvString in $csvStrings) { $columns = $csvString.Split("`r`n")[0].Split(",") | ForEach-Object { $_ = $_.Trim() # Remove the "" if ([Regex]::new("^`"(.*)`"$").IsMatch($_)) { [Regex]::new("^`"(.*)`"$").Match($_).Groups[1].Value } else { $_ } } foreach ($column in $columns) { $columnNames[$column] = $true } } $columnNames = $columnNames.Keys | Sort-Object # Convert each of the CSV strings to CSV objects $csvObjects = @() foreach ($csvString in $csvStrings) { $csvObject = ConvertTo-CsvObject -csvString $csvString if (!$csvObject) { Write-Error "Not all CSV strings to combine could be converted to CSV objects." return $null } # Add in additional columns if they don't exist for each row foreach ($csvRow in $csvObject) { foreach ($columnName in $columnNames) { if ($columnName -notIn $csvRow.PSObject.Properties.Name) { $csvRow | Add-Member -NotePropertyName $columnName -NotePropertyValue $null -Force } } } $csvObjects += $csvObject } # Combine the CSV objects $combinedCsvObject = @() foreach ($csvObject in $csvObjects) { foreach ($csvRow in $csvObject) { $combinedCsvObject += $csvRow } } # Convert the combined CSV into a CSV string $combinedCsvString = ConvertTo-CsvString -csvObject $combinedCsvObject if ([String]::IsNullOrWhiteSpace($combinedCsvString)) { Write-Error "Failed to convert combined CSV object into CSV string." return $null } # Return the combined CSV string return $combinedCsvString } |