如何将 headers 添加到没有的 CSV 文件中?

How do I add headers into a CSV that does not have one?

听起来很简单,但我做不到...

$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

这应该有效:

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

是这一行:

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

您正在将数据传送到 export-csv cmdlet。该命令没有输出,因此 $file 将为空。 $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