简体   繁体   English

循环浏览目录并使用Powershell删除csv标头

[英]Loop through directory and remove csv headers with Powershell

I'm trying to loop through the directory DirIn, remove the first two lines from each csv file, and then save those files in a new directory DirOut. 我试图遍历目录DirIn,从每个csv文件中删除前两行,然后将这些文件保存在新目录DirOut中。 The following code is what I've pieced together from other forums, but I cannot get the code to work. 下面的代码是我在其他论坛上拼凑而成的,但是我无法使这些代码正常工作。 Any help would be greatly appreciated. 任何帮助将不胜感激。

gci "DirIn\*.csv" | % {(gc $_ | select -Skip 2) | sc "DirOut\$_" }

You're losing your $_ reference to the file when piping inside the ForEach-Object loop. ForEach-Object循环中进行管道传递时,您将丢失对文件的$_引用。 Use the -PipelineVariable parameter to get around that. 使用-PipelineVariable参数可以解决该问题。

gci "DirIn\*.csv" -PipelineVariable 'File' | % {(gc $File | select -Skip 2) | sc "DirOut\$($File.Name)" }

To show LotPings answer in a readable and maintainable format... 要以可读且可维护的格式显示LotPings答案...

ForEach ($File in (Get-ChildItem "DirIn\*.csv")) {
    (Get-Content $File | Select-Object -Skip 2) |
        Set-Content "DirOut\$($File.Name)"
}

Best practice is to not use aliases in script files. 最佳做法是不要在脚本文件中使用别名。

gci "DirIn\*.csv" | % {(gc $_ | select -Skip 2) | sc "DirOut\$($_.Name)" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM