Convert to PSObject and then export to CSV
All that "foreach" is not needed. Just convert your hash to PSObject, then export!
This example uses an ArrayList to store HashTables, and then exports the ArrayList to CSV.
[System.Collections.ArrayList]$collection = New-Object System.Collections.ArrayList($null) $SiteInfo = @{} $SiteInfo.Url = "http://some.url.com" $SiteInfo.Owner = "Joe Smith" $collection.Add((New-Object PSObject -Property $SiteInfo)) | Out-Null $SiteInfo = @{} $SiteInfo.Url = "http://another.url.com" $SiteInfo.Owner = "Sally Jones" $collection.Add((New-Object PSObject -Property $SiteInfo)) | Out-Null $collection | Export-Csv "UsageReport.csv" -NoTypeInformation -Encoding UTF8 -Delimiter '|'
Things that won't work.
Please note that while this works:
$collection.Add((New-Object PSObject -Property $SiteInfo))
... here are some things that will NOT work:
Leaving one set of brackets will NOT work:
$collection.Add(New-Object PSObject -Property $SiteInfo)
Leaving the -property argument label will NOT work:
$collection.Add((New-Object PSObject $SiteInfo))
Just using += will NOT work:
$collection += $SiteInfo
To do this, you will receive error messages and / or strange entries in the CSV file.
Why is Out-Null?
Note: $collection.Add() displays the index of the highest valid index when it starts. | Out-Null | Out-Null just throws that number out if you don't want it.
source share