使用powershell合并两个文件夹并根据源文件夹重命名文件

Using powershell to merge two folders and rename files based on source folder

我有一组这样的文件:

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 .15_09_22\
Get-ChildItem *\* | ForEach {$_.MoveTo("$($_.Directory.Parent.FullName)$($_.Directory.Name)_$($_.Name)")}

这会移动文件,但不会删除目录,并且有点难以阅读。所以也许这样更合理:

cd .15_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()
}