Author Posts

April 5, 2017 at 3:50 pm

I am trying to display the contents of column 1 and 2 in a CSV file. When I used the code below,

$csv = Import-Csv C:transfer.csv
$csv | Export-Csv transfer2.csv -NoTypeInformation
$csv | Select-Object col1, col2 ## This line returns the header col1, col2 but there is no data.

Transfer2.csv does contain data from transfer1.scv in column 1 & 2. But if I use Select-Object col1, col2, column1 and 2 come back completely empty. There was no error message. What am I doing wrong? What do I need to do to show contents of column 1 and 2 from transfer.csv?

April 5, 2017 at 3:52 pm

$csv contains the original transfer.csv. You exported that to transfer2.csv, but that did not change the contents of the $csv variable.

What does the header of transfer.csv look like?

April 5, 2017 at 4:01 pm

$csv | Select-Object col1, col2 returns nothing probably because the column headers are not called col1, col2
The code

($Csv | Get-Member | ? { $_.MemberType -eq 'NoteProperty' } | select -First 2).Name

returns the names of the first 2 columns.

Now try this:

$csv = Import-Csv C:transfer.csv
$csv | Export-Csv transfer2.csv -NoTypeInformation
$Csv | select ($Csv | Get-Member | ? { $_.MemberType -eq 'NoteProperty' } | select -First 2).Name | FT -a 

April 5, 2017 at 4:01 pm

Thanks for the feedback. I am simply trying to display the contents of column1 and column 2 of transfer.csv to see if the data is read correctly. Ultimately, what I am trying to do is use column 1 and 2 of a CSV file as the input variables to a function which will write the result to column3. But I can't even seem to get the contents of column1 and 2 and I am not sure what I am doing wrong.

April 5, 2017 at 4:02 pm

Again, what's the header of the CSV look like?

April 5, 2017 at 4:08 pm

transfer.csv has three columns and this is what it looks like:

Source Destination Status
—— ———– ——
C:\file1.txt C:\Users\thchen\Desktop\ASPCTest\
C:\file2.txt C:\Users\thchen\Desktop\ASPCTest\
C:\file3.txt C:\Users\thchen\Desktop\ASPCTest\
C:\file4.txt C:\Users\thchen\Desktop\ASPCTest\

So the header of the three columns are 'Source', 'Destination' and 'Status'.

April 5, 2017 at 4:10 pm

Thank you both. I use "$csv | Select-Object Source, Destination, Status" and now it works!

April 5, 2017 at 4:11 pm

Yeah, so I think that's the point of confusion.

When dealing with a CSV, Select-Object treats the COLUMN HEADERS as properties. You you could Select Source, Destination, and Status, because those are your column headers. But "Col1" isn't a thing. That's why – as noted above – you're getting blanks. Select-Object treats non-existent properties as new, blank properties, and outputs them.