npocmaka
npocmaka

Reputation: 57252

Import-Csv from string instead from a file?

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"

Upvotes: 20

Views: 19053

Answers (2)

wtgreen
wtgreen

Reputation: 61

Even better:

$csv_content1 = ConvertFrom-CSV -delim ';' -Input @"
"col1"; "col2"
val11 ; val12
val21 ; val22
"@

Upvotes: 6

Joey
Joey

Reputation: 354516

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.

Upvotes: 37

Related Questions