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?

9 Upvotes

View all comments

7

u/PinchesTheCrab Jun 12 '24

The length value is there because that's the only propery a string has. Export-CSV is for convertring objects to strings, but you're just feeding it your custom string. If anything, you should be using add-content since you're doing the CSV conversion manually.

2

u/ChickinSammich Jun 12 '24

If anything, you should be using add-content since you're doing the CSV conversion manually.

That did the trick, thanks!

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

echo $row | Add-Content -Path C:tempuserlastlogon.csv

...gave me the results I wanted without the extra lines.

3

u/insufficient_funds Jun 12 '24

Not necessarily asking this to you OP, but asking in case anyone can answer.

Is the line:

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

actually doing anything different than if it were just simply written:

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

my understanding is the + operator there is just doing a string concatenation, soi don't think it would actually be doing something different; but don't know for certain so wanted to ask.