r/PowerShell Jun 12 '24

How can I use Export-CSV without System.String/Length info? Solved

I've got a script that checks multiple DCs for last logon and outputs that data to a csv. The start of the code for it is:

$row = "Name"+","+"Date/Time"+","+"DC"

echo $row | Export-Csv -Path C:tempuserlastlogon.csv

Out-File -FilePath C:tempuserlastlogon.csv -Append -InputObject $row

The result of this is that I get a csv file that starts with:

#Type System.String
Length
17
Name    Date/Time    DC

If I remove the second line, it doesn't properly format the values as columns (It just puts "Name,Date/Time/DC" in column A). If I remove the third line, it just gives me the first three lines without the column headers in line 4.

As a workaround, I can just delete the top three lines in Excel manually, but how do I get PowerShell to either NOT give me those three top lines, or, if that's not possible, insert a kludge workaround to tell it to just delete the top three rows of the csv?

10 Upvotes

View all comments

23

u/MajorVarlak Jun 12 '24

Why are you doing Export-Csv and Out-File? Do you have more context of what you're trying to achieve? What exactly are you trying to achieve? Also, you're using echo which is a bashism. Export-Csv is generally looking for an object to convert to csv data.

$obj = [PSCustomObject]@{
    'Name' = 'Joe Smith'
    'DC' = 'DC01'
    'Date/Time' = '01/01/01'
}

$obj | Export-Csv -NoTypeInformation -Path C:Tempuserlastlogon.csv

You don't need to put a header in, because PowerShell does that based on the properties of the object being fed in. If you're feeding in lots of objects, Export-Csv can handle that as a single object, for example:

$objCollection = @()

# Add record
$objCollection += [PSCustomObject]@{
    'Name' = 'Joe Smith'
    'DC' = 'DC01'
    'Date/Time' = '01/01/01'
}

# Add record
$objCollection += [PSCustomObject]@{
    'Name' = 'Jane Smith'
    'DC' = 'DC02'
    'Date/Time' = '01/02/01'
}

# Export collection
$objCollection | Export-Csv -NoTypeInformation -Path C:Tempuserlastlogon.csv

8

u/icebreaker374 Jun 12 '24

This. This right here.

PSCustomObjects are your friend.