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"
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With