Why is Move-Item putting a folder inside another folder with the same name?

November 14, 2026 4 answers
Asked by _nearly__elsewhere

I'm moving the contents of one directory into another with PowerShell. My function builds each destination from the destination path plus the item's name. When a folder with that name already exists, the source folder ends up nested inside it instead of merging. Doesn't -Force prevent that?

Answers

b3~gasket_582

The destination you build for synced_imgs is the existing synced_imgs folder itself. Move-Item sees that as a container and moves the source folder into it, giving you synced_imgs/synced_imgs. The -Force switch doesn't turn a directory move into a recursive merge.

If you want to combine the contents, handle directories separately: create the matching destination directory if needed, then move their children into it, repeating for subdirectories. Decide what should happen when files with the same name already exist before using -Force.

Jemwick.42:

Moving only files recursively also needs some path handling. You'll have to preserve their paths relative to the source and create the destination directories first.

Reply to this answer
_slightly+unsorted

Check the paths as the loop runs. Print or inspect $_.FullName and the value passed to -Destination for both a file and a folder. Also check the destination argument passed to the function. If it already includes the folder name, appending $_.Name can put you one level deeper than intended.

Passing just the parent destination is appropriate when you want to move a whole folder there. Don't assume that alone will merge it with an existing folder, though. Test that case separately.

Reply to this answer
8t+oddment.42

If a whole directory tree needs merging, take a look at Robocopy as an alternative to writing the recursion yourself. Check its move and overwrite options carefully, and test against disposable folders first. It's a different tool with its own behavior, not a drop-in Move-Item switch.

Reply to this answer
x81+buswatch_406

The function may be doing more work than you need if the destination doesn't already contain matching folders. A direct Move-Item to the parent directory can move a whole folder without a loop. The merge case is the part that needs extra handling.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions