Creating Readable CSV-and HTML-Output

by Aug 27, 2013

When you convert PowerShell results to CSV or HTML output, you may have discovered that some properties don't display correctly. PowerShell cannot correctly convert arrays to strings and instead displays the array data type. Here's a sample:

# use extension "hta" to open the file in
# a special HTML viewer instead of your browser:
$Path = "$env:temp\tempfile.hta"

Get-Service | 
  Select-Object -Property DisplayName, Status, DependentServices |
  ConvertTo-Html |
  Set-Content -Path $Path

Invoke-Item -Path $Path 

The result looks similar to this:

Since the property "DependentServices" is an array, it is not converted to a string but instead PowerShell displays the underlying data type.

The solution is to add a ForEach-Object loop and preprocess any array property – use the operator -join to convert it manually into a string:

# use extension "hta" to open the file in
# a special HTML viewer instead of your browser:
$Path = "$env:temp\tempfile.hta"

Get-Service | 
  Select-Object -Property DisplayName, Status, DependentServices |
  ForEach-Object {
    $_.DependentServices = $_.DependentServices -join ', '
    $_
  } |
  ConvertTo-Html |
  Set-Content -Path $Path

Invoke-Item -Path $Path

Now, the result looks a lot better:

Twitter This Tip! ReTweet this Tip!