Sarah
Sarah

Reputation: 47

Value doesn't appear on next line

I am trying to achieve an output with some contents in the table. All looks good to me, but the only issue I am facing is that the value under H1 column appears in same line.

Is there a way, I could make this appear in next line? Of course, removing commas and braces.

Here is the code:

$Csv = Import-Csv -Path $file

$Csv | Group-Object -Property Name | ForEach-Object -Process {
    [PSCustomObject]@{
      N1 = $_.Name
      T1 = ($_.Group.TOtal |Measure -sum).Sum
      H1 = $_.Group.Hired
      C1 = $_.Group.Count
      
    }
}

Current Output:

N1     T1 H1                 C1
--     -- --                 --
John    3 2002                1
David 150 {2011, 2003, 2011}  3
Steve  55 {2012, 2003}        2
Jason 550 {2001, 2002}        2

Desired Output:

N1     T1 H1                 C1
--     -- --                 --
John    3 2002                1
David 150 2011                3
          2003
          2011
...

Upvotes: 1

Views: 54

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

You can get the desired output by explicitly calling Format-Table like this:

$CSV |Format-Table N1,T1,@{Name='H1';Expression={$_.H1 -join "`n"}},C1 -Wrap 

The calculated property expression:

{$_.H1 -join "`n"}

makes Format-Table display H1 as a multi-line string. -Wrap prevents Format-Table from truncating multi-line strings - giving us something like:

N1     T1 H1             C1
--     -- --             --
John    3 2002            1
David 150 2011            3
          2003
          2011
Steve  55 2012            2
          2003
Jason 550 2001            2
          2002

If you want to preserve the newlines when exporting to a CSV file, use Select-Object instead:

$CSV |Select-Object N1,T1,@{Name='H1';Expression={$_.H1 -join "`n"}},C1 |Export-Csv .\output_with_newlines.csv -NoTypeInformation

Converting to HTML is as easy as piping the resulting objects to ConvertTo-Html -As Table:

$CSV |Select N1,T1,@{Name='H1';Expression={$_.H1 -join "`n"}},C1 |ConvertTo-Html -As Table |Set-Content .\path\to\report.html

By default, your browser will render the newlines as regular spaces, but this can be solved by injecting a bit of CSS:

$style = @'
<style>
  table {
    white-space: pre;
    vertical-align:top;
  }
</style>
'@

$CSVMultiLine = $CSV |Select N1,T1,@{Name='H1';Expression={$_.H1 -join "`n"}},C1 
$CSVMultiLine |ConvertTo-Html -As Table -Head $style |Set-Content .\path\to\report.html

white-space: pre will render newlines as-is, and vertical-align: top ensures the first line of each column is always aligned. Add your own styling as required.

Upvotes: 3

Related Questions