Powershell – Export custom object to CSV


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:


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

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


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.


$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"


tmp tmp2, hostname