使用 PowerShell 将具有特定扩展名的所有文件从多个子目录移动到相同的子目录结构中

Move all files with a certain extension from multiple subdirectories into same subdirectory structure using PowerShell

我正在尝试读取多个子目录中的多个 CSV 文件,并使用 PowerShell 脚本根据过滤器进行一些行删除。

Get-ChildItem -Path J:\new -Recurse -Filter daq*.csv | ForEach-Object {
    Get-Content $_.FullName | Where {
        $_ -notmatch "serverTime"
    } | Out-File $_.FullName
}

但我希望输出与源文件位于相同的目录结构中。 目录结构如下:

root/
   sub_dir1/
       1.csv
       2.csv
   sub_dir2/
       1.csv
       2.csv

有什么办法可以做到吗?

可能不是最佳的,甚至不是惯用的,但以下内容在快速测试中有效:

Get-ChildItem -Path J:\new -Recurse -Filter daq*.csv | 
    ForEach-Object {
        $origFile = $_
        $filteredContent = Get-Content $origFile.FullName | Where{$_ -notmatch "serverTime"} 
        $filteredContent | Out-File $origFile.FullName
    }

我们所做的就是加载每个文件的内容并将其过滤到 $filteredContent,然后将其写回原始文件。

另一个选项(由 提供)是将 Get-Content 命令包装在括号中,这会强制加载全部内容,然后向下传递到管道。这将提供更短的代码,但可以说它不太容易理解,例如

Get-ChildItem -Path J:\new -Recurse -Filter daq*.csv | 
    ForEach-Object {
        $origFile = $_
        ( Get-Content $origFile.FullName ) | 
            Where{$_ -notmatch "serverTime"} | 
            Out-File $origFile.FullName
    }