How can I merge folders of the same name in powershell?

162 views Asked by At

I have a list of poorly maintained directories which should have the same subdirectories, but over time some of these directories have wound up at the wrong level. I want to move these subdirectories to the correct level using PS

Directories Should be Structured:

Top Level
     WrapperFolder
         SubFolder1
             Files
         SubFolder2
             Files

But I have directories that look like:

Top Level
    SubFolder1
        Files
    WrapperFolder
        SubFolder1
            Files

I want to move SubFolder1 from the Top Level and merge it with SubFolder1 in the WrapperFolder

I tried:

move-item -path "c:\TopLevel\SubFolder" -dest "C:\TopLevel\WrapperFolder\"

However this throws an IOException when the same directory name already exists. Is there a way to merge these directories or will I need to move the files to the correct folder recursively and delete the original folder?

1

There are 1 answers

0
kconsiglio On

If you want to merge the folders like how file explorer would, you'll need to use a windows shell com object. This solution here is essentially what you need except instead of using the CopyHere function we will use MoveHere to move the directory. This solution based on that example.

 $sourcePath = "C:\Users\path\New folder\SubFolder1"
 $destinationPath = "C:\Users\path\New folder\WrapperFolder"
 $sourceFolder = (new-object -com shell.application).NameSpace($sourcePath)
 $destinationFolder = (new-object -com shell.application).NameSpace($destinationPath)

 $destinationFolder.MoveHere($sourceFolder,16)

We pass $sourceFolder and 16 which is a flag value corresponding to the option (reference):

Respond with "Yes to All" for any dialog box that is displayed.

With that option, the folder will be merged and any files with the same names will be overwritten. There are other options for example '8', if you would like to not overwrite files:

Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.