I would like to be able to change this string:
$Result
Header 1,Text 1,Text 11,,,,,
Header 2,Text 2,Text 22,,,,,
Header 3,Text 3,Text 33,,,,,
Header 4,,Text 44,,,,,
In to this string:
$Result
Header 1,Header 2,Header 3,Header 4
Text 1,Text 2,Text 3,,
Text 11,Text 22,Text 33,Text 44
I managed to do this when it only concerns one header and one text item. But I can't figure out how to do this dynamically, in case I don't know how many text items will follow. This string will then be imported by ConvertFrom-Csv
for later use.
My current code which works for one header and one text item:
$Result | ForEach-Object {$Header += "$($_.Split(',')[0]),"; $Content += "$($_.Split(',')[1]),"}
$Result = "$Header`n$Content"
Solution, thanks to the guys below:
Function ConvertTo-ReverseCSV {
[CmdletBinding(SupportsShouldProcess=$True)]
Param (
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String] $String
)
PROCESS {
$StringMax = 0
$h = @()
$String.split("`n") | % {
$a = $_.split(",")
$h += ,$a
if($a.length -gt $StringMax) { $StringMax = $a.length }
}
for($j = 0; $j -lt $StringMax; $j++) {
for($i = 0; $i -lt $h.length; $i++) {
$Result += "$($h[$i].split("`n")[$j]),"
}
$Result +="`n"
}
Write-Output $Result
}
}