除非你将输入文件读入内存完整的,预先的,您无法安全地读取和写回给定管道中的同一文件。
Specifically, a command such as Import-Csv file.csv | ... | Export-Csv file.csv
will erase the content of file.csv
.[1]
最简单的解决方案是将读取输入文件的命令括起来(...)
,但请注意:
应用于您的命令:
$RootPath = "D:\SomeFolder"
Get-ChildItem $RootPath -Recurse -Include *.csv -OutVariable csvFiles |
ForEach-Object{
(Import-CSV $_.FullName) | # NOTE THE (...)
Select-Object Test_Name, Test_DataName, Device_Model, Device_FW,
Data_Avg_ms, Data_StdDev |
Export-Csv $_.FullName -NoType -Force
}
请注意,我已经使用过-OutVariable csvFiles
为了收集输出变量中的 CSV 文件信息对象$csvFiles
。您尝试通过以下方式收集文件路径$csvFilePaths = ...
不起作用,因为它试图收集Export-Csv
's输出,但是Export-Csv
不产生输出。
另外,为了安全起见,我改变了Import-Csv
论证来自$_
to $_.FullName
为了保证Import-Csv
找到输入文件(因为,遗憾的是,文件信息对象$_
被绑定为string, which 有时扩展到仅仅是文件名).
A 更安全的解决方案将会是首先输出到临时文件,并且(仅)在成功完成后替换原始文件。
无论采用哪种方法,替换文件都将具有默认的文件属性和权限;如果原始文件具有要保留的特殊属性和/或权限,则必须显式重新创建它们。
[1] Note that in other contexts (on Windows) you may simply get an error that doesn't result in the input file's content getting erased; e.g., the following pipeline: Get-Content file.txt | ForEach-Object { "[$_]" } | Set-Content file.txt
reports error The process cannot access the file '...\file.txt' because it is being used by another process
, without erasing the content of file.txt