Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import-Csv from string instead from a file?

Tags:

powershell

csv

Is there a way to create a csv object in powershell from variable that contains string? At the moment I need to write content in a temp file and then import it to csv and I want to reduce disk operations:

$some_string | Set-Content $temp_file
$csv_content=Import-Csv $temp_file

EDIT

@Graham Gold , Јοеу thanks for the answers (I've set +1 on both of you) , but seems the Joey's answer is correct.Here's my test:

    $csv_string="
`"col1`" ; `"col2`"
val11 ; val12
val21 ; val22"

$csv_content1 = $csv_string | ConvertFrom-CSV 
$csv_content2 = $csv_string | ConvertTo-CSV 
"
ConvertFrom result:"
$csv_content1
"
ConvertTo result:"
$csv_content2

And the result:

ConvertFrom result:

H1                                                                             
--                                                                             
col1 ; "col2"                                                                  
val11 ; val12                                                                  
val21 ; val22                                                                  

ConvertTo result:
#TYPE System.String
"Length"
"47"
like image 537
npocmaka Avatar asked Jul 05 '13 09:07

npocmaka


People also ask

How do I convert a string to a CSV file in Powershell?

You can use the Export-Csv cmdlet to convert objects to CSV strings. Export-CSV is similar to ConvertTo-CSV , except that it saves the CSV strings to a file. The ConvertTo-CSV cmdlet has parameters to specify a delimiter other than a comma or use the current culture as the delimiter.

How do I import a CSV file?

On the File menu, click Import. In the Import dialog box, click the option for the type of file that you want to import, and then click Import. In the Choose a File dialog box, locate and click the CSV, HTML, or text file that you want to use as an external data range, and then click Get Data.


1 Answers

You can use ConvertFrom-Csv instead:

$csv_content = $some_string | ConvertFrom-Csv -Delim ';'

Import-Csv is little more than a wrapper around Get-Content and ConvertFrom-Csv.

like image 116
Joey Avatar answered Oct 20 '22 16:10

Joey