31 March 2015

Fix "System.Object[]" output when exporting to csv

export data to csv is sometimes broken because everything that is passed to Export-Csv cmdlet is casted as a string before the export.

one solution is to create a pscustomobject and use -Join operator on the troubeling property:


$user = Get-ADUser username -Properties memberof
[pscustomobject]@{
    DN = $user .DistinguishedName
    GivenName = $user .GivenName
    MemberOf = $user .MemberOf -Join ','
    Name = $user .Name
    SamAccountName = $user .SamAccountName
    UserPrincipalName = $user .UserPrincipalName
} | Export-Csv -NoTypeInformation .\user.csv





for a better arrangment Out-String cmdlet can be use in replace of Join operator

$user = Get-ADUser user  -Properties memberof
[pscustomobject]@{
    DN = $user.DistinguishedName
    GivenName = $user.GivenName
    MemberOf = ($user.MemberOf | Out-String).Trim()
    Name = $user.Name
    SamAccountName = $user.SamAccountName
    UserPrincipalName = $user.UserPrincipalName
} | Export-Csv -NoTypeInformation .\user.csv


No comments:

Post a Comment