'Select-Object not selecting object from csv-file

I'm trying to import some csv files to further work with them and export them in the end. They all have two header lines from which i'll only need the second one. I also need to delete most columns except a few. Unfortunately it seems you'll need to decide if you want to skip rows with get-content or exclude columns with import-csv. Neither of those can't do both, so i got a workaround:

$out="bla\bla\out.csv"

$in="bla\bla\in.csv" 

$header= (get-content $in -TotalCount 2 )[-1]

$out = Import-csv $in -Header $header -Delimiter ";"|select column1 | Export-Csv -Path $out -NoTypeInformation

this returns an empty csv with the header name column1. What am i doing wrong?

Edit:

The input csv looks like:

filename;filename;...
column1;column2;...
1;a;...
2;b;...
...

I guess that -Header can't read arrays without single quotation marks, so i'm trying to find a solution to that atm.



Solution 1:[1]

If you know the name of the header you want to filter on, the following should do the trick and only requires reading the file once:

$out = "out.csv"
$in = "in.csv"

Get-Content $in | Select-Object -Skip 1 |
    ConvertFrom-Csv -Delimiter ';' | Select-Object column1 |
        Export-Csv $out -NoTypeInformation

If however, you don't know the name of the header you need to filter on (column1 on example above) but you know it's the first column, it would require an extra step:

$csv = Get-Content $in | Select-Object -Skip 1 | ConvertFrom-Csv -Delimiter ';'
$csv | Select-Object $csv[0].PSObject.Properties.Name[0] | Export-Csv $out -NoTypeInformation

We can get the first object of object array ($csv[0]) and get it's properties by accessing it's PSObject.Properties then select the 1st property (.Name[0] - column1 in this case).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Santiago Squarzon