Powershell – Export custom object to CSV

export-to-csvpowershell

I'm quite new to powershell and struggling with outputting data to a CSV file.
I have a larger code piece but created the below small working example that contains the issue:

$results = @()
$tmp_avs = @('tmp', 'tmp2')
$hostname = 'hostname'
$results += New-Object -TypeName PSObject -Property (@{Hostname=$hostname; avs=$tmp_avs})
$res = $results | ? {$_.avs.Count -gt 0} | Format-Table

$res | Export-Csv -NoTypeInformation "test.csv"

When printing the $res object above in PowerShell I get the output:

avs         Hostname
---         --------
{tmp, tmp2} hostname

That is also the output I would like to receive in the CSV file, but currently I get something like this:

"ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo","shapeInfo","groupingEntry"
"033ecb2bc07a4d43b5ef94ed5a35d280",,,,"Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo",
"9e210fe47d09416682b841769c78b8a3",,,,,
"27c87ef9bbda4f709f6b4002fa4af63c",,,,,
"4ec4f0187cb04f4cb6973460dfe252df",,,,,
"cf522b78d86c486691226b40aa69e95c",,,,,

Is there a possibility to export the $res object in a proper CSV format?

EDIT:
I removed the Format-Table now, which results in the following in the CSV format:

"avs","Hostname"
"System.Object[]","hostname"

There is System.Object[] written instead of the values?

Best Solution

The values are an array. If you run $tmp_avs.ToString(), you will also get System.Object[]

To resolve, replace avs=$tmp_avs with avs=$($tmp_avs -join " ") where is the joining character between elements of your array. It converts the array to a string.

Code:

$results = @()
$tmp_avs = @('tmp', 'tmp2')
$hostname = 'hostname'
$results = New-Object -TypeName PSObject -Property (@{Hostname=$hostname; avs=$($tmp_avs -join " ")})
$res = $results | ? {$_.avs.Count -gt 0} 
$res | Export-Csv -NoTypeInformation "test.csv"

Output:

avs,Hostname
tmp tmp2, hostname