I'm trying to take a csv file with a couple of headings and format it into a nice word document while sorting alphabetically by heading1.
The csv looks like:
heading1,heading2,heading3, - up to heading5
info1,info2....info5
info1,info2....info5
etc etc
Heading1 has a lot of double-ups so the script will look something like: If info1 is the same as the above info1, just print info2 and info3. Else print info 1-3 The problem is I don't understand how to assign variables to the headings in my ForEach loops.
Here is what I've tried:
$previousheading1 = ""
$FormatCSV = Import-Csv -Path $RawCSV.Filename -Header "Heading1", "Heading2", "Heading3", "Heading4", "Heading4" | Sort-Object -Property Heading1
$Heading1= $FormatCSV | Select-Object -ExpandProperty Heading1
$Heading2= $FormatCSV | Select-Object -ExpandProperty Heading2
$heading3= $FormatCSV | Select-Object -ExpandProperty Heading3
$FormatCSV = ForEach-Object {
if ($heading1 -eq $previousHeading1) {
Write-Output ("$Heading2- $Heading3")
Write-Output ("`v")
}
else {
Write-Output ("`v")
Write-Output ("$Heading1")
Write-Output ("$Heading2- $Heading3")
}
$previousHeading1 = ($Heading1)
}
At the moment I'm not getting any output in the terminal so something's clearly going wrong.
I have also tried:
$FormatCSV = Import-Csv -Path $RawCSV.Filename -Header "heading1", "heading2", "heading3", "heading4", "heading5" | Sort-Object -Property tenant
$FormatCSV #This just shows that each entry has been sorted correctly into the nice four lines
Write-Output "The list should be below this" #This is only for the sake of my sanity
$previousHeading1 = ""
foreach ($FormatCSV in $FormatCSV.heading1) {
if ($FormatCSV.heading1-eq $previousHeading1) {
Write-Output ($FormatCSV.heading2, $FormatCSV.heading3)
}
else {
Write-Output ($FormatCSV.heading1)
Write-Output ($FormatCSV.heading2, $FormatCSV.heading3)
}
$previousHeading1 = ($FormatCSV.heading1)
}
The second line ($FormatCSV) I left in so I can see how the data is being organised in the terminal. I have the feeling this is a simple fix and I've missed it. Thanks in advance for the help :)
If it help, I'm using visual basic studio and running this in powershell.
CodePudding user response:
Your first attempt was pretty close - I've made a few changes as follows:
$csv = @"
heading1,heading2,heading3,heading4,heading5
info11,info12,info13,info14,info15
info21,info22,info23,info24,info25
info21,info32,info33,info34,info35
info41,info42,info43,info44,info45
"@
$data = $csv | ConvertFrom-Csv | Sort-Object -Property heading1
$previousheading1 = ""
$data | ForEach-Object {
if ($_.heading1 -eq $previousHeading1) {
Write-host "`t$($_.heading2)`t$($_.heading3)"
}
else {
Write-host "$($_.heading1)`t$($_.heading2)`t$($_.heading3)"
}
$previousHeading1 = $_.heading1
}
output:
info11 info12 info13
info21 info22 info23
info32 info33
info41 info42 info43
I'll leave generating the Word Document as an exercise for the reader :-)