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

北城以北 提交于 2021-02-08 11:21:51

问题


I have a set of files like this:

2015_09_22
|____ foo
     |____ common.ext
     |____ common.1.ext
     |____ common.2.ext
     |____ common.3.ext
|____ bar
     |____ common.ext
     |____ common.1.ext
     |____ common.2.ext

I want to merge them into a structure like this, using the source folder name as a string to prepend to the filename:

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

The format of {date}\foo and {date}\bar is fixed but the contents could have a variable number of files with those names.


回答1:


You could use something like:

cd .\2015_09_22\
Get-ChildItem *\* | ForEach {$_.MoveTo("$($_.Directory.Parent.FullName)\$($_.Directory.Name)_$($_.Name)")}

This moves the files, but doesn't remove the directories, and is a little hard to read. So maybe this is more reasonable:

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()
}


来源:https://stackoverflow.com/questions/32728229/using-powershell-to-merge-two-folders-and-rename-files-based-on-source-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!