如何解决带有双引号的 Powershell 外文件字符串转换为单列 CSV
我想知道如何使用 PowerShell 将带有双引号的字符串输出到单列 CSV 中。
这是我与此标题一起使用的 csv 文件:
Name | output 1 | output 2 | output 3 |
这是我目前拥有的 PowerShell 代码:
$name = 'Peter Parker'
$out1 = 'testing'
$out2 = -join('"',"21,22,23",'"');
$out3 = 'output'
$text = "$name,$out1,$out2,$out3"
Write-Output $text
$text | Out-File .\test.csv -Encoding ascii -Append
Get-Content -Path .\test.csv
我要找的结果是这样的:
Name | output 1 | output 2 | output 3 |
Peter Parker | testing | "21,23" | output |
但是我得到了当前代码的结果:
Name | output 1 | output 2 | output 3 |
Peter Parker | testing | "21 | 22 | 23" | output |
有没有办法或解决办法来实现我的目标?
谢谢!
解决方法
为什么不让 Powershell 为您完成这项工作? Powershell 可以轻松处理结构化数据和 csv 文件。
示例:
[PSCustomObject]@{
Name = 'Peter Parker'
out1 = 'testing'
out2 = ('"',"21,22,23",'"') -join ''
out3 = 'output'
} |
Export-Csv -Path .\test.csv -NoTypeInformation -Delimiter ','
当然,您可以轻松地再次导入此数据:
Import-Csv -Path .\test.csv -Delimiter ','
结果是:
Name out1 out2 out3
---- ---- ---- ----
Peter Parker testing "21,23" output
您可能要记住,Powershell 是为管理员设计的,而不是为软件开发人员设计的。它试图让你的事情变得容易。 ;-)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。