Search code examples
powershellfile-manipulation

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


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.


Solution

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