【问题标题】:Powershell Out-File String with Double Quotes into Single Column CSV带有双引号的 Powershell 输出文件字符串到单列 CSV
【发布时间】:2021-06-02 19:34:39
【问题描述】:

我想知道如何使用 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, 22, 23" | output    |

但是我得到了当前代码的这个结果:

Name          | output 1 | output 2 | output 3 |
Peter Parker  | testing  | "21      | 22       | 23"   | output  |

有没有办法或解决办法来实现我的目标?

谢谢!

【问题讨论】:

    标签: string powershell csv file-io double-quotes


    【解决方案1】:

    为什么不让 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,22,23" output
    

    您可能要记住,Powershell 是为管理员设计的,而不是软件开发人员。它试图让你的事情变得容易。 ;-)

    【讨论】:

    • 我明白了!我从不尝试这种方法。谢谢!
    猜你喜欢
    • 2021-05-11
    • 2014-04-22
    • 2015-09-16
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2017-02-26
    相关资源
    最近更新 更多