Liturgist Liturgist - 3 months ago 28
PowerShell Question

Export-Csv emits Length and not values

I want to read a CSV file and output a CSV file with only one (1) field. I have tried to create a concise example.

PS C:\src\powershell> Get-Content .\t.csv
field1,field2,field3
1,2,3
4,55,6
7,888,9

PS C:\src\powershell> Import-Csv -Path .\t.csv | `
>> ForEach-Object {
>> $_.field2 `
>> } | `
>> Export-Csv -Path .\x.csv -NoTypeInformation
>>


The problem is that the Length of field2 is written to the exported CSV file. I want the field header to be "field2" and the values to be the value from the original CSV file. Also, I only want quotes where they are required; not everywhere.

I have read Export-CSV exports length but not name and Export to CSV only returning string length. But these do not seem to address producing an actual CSV file with a header and one field value.

PS C:\src\powershell> get-content .\x.csv
"Length"
"1"
"2"
"3"

Answer

CSV object uses note properties in each row to store its fields so we'll need to filter each row object and leave just the field(s) we want using Select-Object cmdlet (alias: select), which processes the entire CSV object at once:

Import-Csv 1.csv | select field2 | Export-Csv 2.csv -NoTypeInformation

Note, there's no need to escape the end of line if it ends with |, {, (, or ,.
It's possible to specify several fields: select field2, field3.

As for having doublequotes only where needed, it would have to be done manually using a regexp:

Import-Csv 1.csv |
    select field2 |
    ConvertTo-Csv -NoTypeInformation |
    %{ $_ -replace '"(\S*?)"', '$1' } |
    Out-File 2.csv -Encoding ascii