如何将标题添加到没有标题的CSV中?

时间:2015-02-16 17:21:35

标签: powershell csv

听起来很容易,但我无法让它发挥作用......

$file = 'D:\TESTING.csv'

Set-Content $file "1,2,3"

$file = import-csv $file -Header a , b , c | export-csv $file 

echo $file

期望的输出:

a b c
- - -
1 2 3

实际输出:

nothing

2 个答案:

答案 0 :(得分:7)

这一行:

$file = import-csv $file -Header a , b , c | export-csv $file

您将数据传输到export-csv cmdlet。该命令没有输出,因此$file将为null。此外,$file包含输出的路径。为什么要将其更改为文件内容?

假设您要同时导出数据并将其保留在会话中,您可以执行以下操作:

$filedata = import-csv $file -Header a , b , c  
$filedata | export-csv $file -NoTypeInformation

您也可以使用Tee-Object

在一行中执行此操作
Import-CSV $file -Header a , b , c | Tee-Object -Variable $filedata | Export-CSV $file -NoTypeInformation

答案 1 :(得分:1)

这应该有效:

import-csv test.csv -Header "Name" | export-csv test.csv -NoTypeInformation