使用powershell合并两个文件夹并基于源文件夹重命名文件

使用powershell合并两个文件夹并基于源文件夹重命名文件,powershell,file-manipulation,Powershell,File Manipulation,我有一组这样的文件: 2015_09_22 |____ foo |____ common.ext |____ common.1.ext |____ common.2.ext |____ common.3.ext |____ bar |____ common.ext |____ common.1.ext |____ common.2.ext 我想将它们合并到如下结构中,使用源文件夹名称作为字符串作为文件名的前缀: 2015_0

我有一组这样的文件:

2015_09_22
|____ foo
     |____ common.ext
     |____ common.1.ext
     |____ common.2.ext
     |____ common.3.ext
|____ bar
     |____ common.ext
     |____ common.1.ext
     |____ common.2.ext
我想将它们合并到如下结构中,使用源文件夹名称作为字符串作为文件名的前缀:

2015_09_22
|____ foo_common.ext
|____ foo_common.1.ext
|____ foo_common.2.ext
|____ foo_common.3.ext
|____ bar_common.ext
|____ bar_common.1.ext
|____ bar_common.2.ext

{date}\foo和{date}\bar的格式是固定的,但内容中可能有数量可变的文件,这些文件的名称都是固定的。

您可以使用类似于:

cd .\2015_09_22\
Get-ChildItem *\* | ForEach {$_.MoveTo("$($_.Directory.Parent.FullName)\$($_.Directory.Name)_$($_.Name)")}
这会移动文件,但不会删除目录,并且有点难以读取。所以这可能更合理:

cd .\2015_09_22\

foreach ($dir in (Get-ChildItem -Directory)) {
    foreach ($file in (Get-ChildItem $dir -File)) {
        $dest = "$($file.Directory.Parent.FullName)\$($file.Directory.Name)_$($file.Name)"
        $file.MoveTo($dest)
    }
    $dir.Delete()
}

我不在乎目录是否被删除(我只希望文件被移动而不是复制,因为它们很大),所以第一个解决方案可以工作。