powershell - 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
有人请帮助获得解决方案...
解决方案
如果您想要的结果只是将数组中的第一个值与第二个值结合起来,以此类推,一个简单的 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"
推荐阅读
- c - 无需管道将数据从子进程传递到父进程
- c# - C# Object to Json to Xml,如何为数组项生成xml元素
- c - 如何让我的函数获取用户输入并将其存储在数组中?
- datetime - 计算多条记录的重叠时间
- google-api - Google drive API - 使用 file_id 获取父文件夹?
- node.js - 使用 multer 在 mongoDb 中存储和获取图像时遇到问题?
- sql - 从不同的表中选择数据并将计算插入到新表中
- docker - 重启后 Docker overlay2 文件丢失为空(Ubuntu 14.04)
- php - MySQL Text 数据类型的行为类似于 Int 数据类型
- spring - 当请求输入无效时,控制器周围的 Spring AOP 不起作用