从字符串而不是从文件导入-Csv?

npo*_*aka 15 csv powershell

有没有办法在powershell中从包含字符串的变量创建一个csv对象?目前我需要在临时文件中写入内容然后将其导入csv,我想减少磁盘操作:

$some_string | Set-Content $temp_file
$csv_content=Import-Csv $temp_file
Run Code Online (Sandbox Code Playgroud)

编辑

@Graham Gold,感谢你的答案(我已经为你们两个人设置了+1),但似乎Joey的答案是正确的.这是我的测试:

    $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
Run Code Online (Sandbox Code Playgroud)

结果如下:

ConvertFrom result:

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

ConvertTo result:
#TYPE System.String
"Length"
"47"
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 28

你可以ConvertFrom-Csv改用:

$csv_content = $some_string | ConvertFrom-Csv -Delim ';'
Run Code Online (Sandbox Code Playgroud)

Import-Csv只不过是一个包装Get-ContentConvertFrom-Csv.


小智 5

更好的是:

$csv_content1 = ConvertFrom-CSV -delim ';' -Input @"
"col1"; "col2"
val11 ; val12
val21 ; val22
"@
Run Code Online (Sandbox Code Playgroud)