powershell - Export-Csv emits Length and not values -


i want read csv file , output csv file 1 (1) field. have tried create 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 length of field2 written exported csv file. want field header "field2" , values value original csv file. also, want quotes required; not everywhere.

i have read export-csv exports length not name , export csv returning string length. these not seem address producing actual csv file header , 1 field value.

ps c:\src\powershell> get-content .\x.csv "length" "1" "2" "3" 

csv object uses note properties in each row store fields we'll need filter each row object , leave field(s) want using select-object cmdlet (alias: select), processes entire csv object @ once:

import-csv 1.csv | select field2 | export-csv 2.csv -notypeinformation 

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


to strip unneeded doublequotes, general multi-field case:

import-csv 1.csv |     select field2 |     %{         $_.psobject.properties | %{ $_.value = $_.value -replace '"', [char]1 }         $_     } |     convertto-csv -notypeinformation |     %{ $_ -replace '"(\s*?)"', '$1' -replace '\x01', '""' } |     out-file 2.csv -encoding ascii 

simplified one-field case:

import-csv 1.csv |     select field2 |     %{         $_.field2 = $_.field2 -replace '"', [char]1         $_     } |     convertto-csv -notypeinformation |     %{ $_ -replace '"(\s*?)"', '$1' -replace '\x01', '""' } |     out-file 2.csv -encoding ascii 

a tricky case of embedded quotes inside field solved temporary replacing them control character code 01 (there few can used in typical non-broken text file: 09/tab, 0a/line feed, 0d/carriage return).


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -