首页 > 解决方案 > Powershell - 明智地附加 CSV 列

问题描述

我有一个数组,我想将它导出为 CSV,我使用下面的代码。

[string[]] $Params = "Foo", "Bar"
$Params | out-file "D:\Output.csv" -Encoding ascii -Force -Append

#Output
Foo
Bar
Foo1
Bar1
Foo2
Bar2

它以行方式附加CSV,我希望它以列方式如下所示,

Foo, Bar
Foo1, Bar1
Foo2, Bar2

有人请帮助获得解决方案...

标签: powershell

解决方案


如果您想要的结果只是将数组中的第一个值与第二个值结合起来,以此类推,一个简单的 for 循环就可以了:

[string[]] $Params = "Foo", "Bar","Foo1", "Bar1","Foo2", "Bar2"
$result = for ($i = 0; $i -lt $Params.Count -1; $i+=2 ) {
    # if any of the strings in the $Params array contains spaces 
    # or comma's I would strongly suggest quoting the output.
    '"{0}","{1}"' -f $Params[$i], $Params[$i+1]
}

# output on screen
$result

# output to CSV (no headers)
$result | Set-Content -Path 'D:\output.csv'

上述输出:

"Foo","Bar"
"Foo1","Bar1"
"Foo2","Bar2"

推荐阅读