Why does Move-Item nest an existing folder instead of merging its contents?

August 5, 2026 3 answers
Asked by MellowCedar47
I wrote a PowerShell function that moves the contents of one directory into another and skips .DS_Store entries: function PSTransfer { param ( [string]$BasePath, [string]$DestinationPath ) Get-ChildItem -Path "$BasePath/*" -Force | ForEach-Object { if (!($_.FullName -like "*.DS_Store")) { Move-Item -LiteralPath $_.FullName -Destination "$DestinationPath/$($_.Name)" -Force } } } For example, if both paths contain a folder named synced_imgs, I want the files from the source folder to be placed into the existing destination folder. Instead, Move-Item creates DestinationPath/synced_imgs/synced_imgs and puts the source contents there. Running the function repeatedly nests the folder further. I assumed -Force would merge the directories, but it does not. What should the destination argument be, and how can I avoid the extra directory level?

Answers

GraniteFox63
The function call should look like this: PSTransfer -BasePath /Users/user/BasePath -DestinationPath /Users/user/DestinationPath Inside the loop, use: Move-Item -Path $_ -Destination $DestinationPath -Force Do not append $_.Name to the destination unless you are intentionally supplying a new target path. The extra name is what causes the existing folder to be treated as a container and produces the nested result.
Reply to this answer
CopperLark22
For a folder move, provide only the destination parent path. For example, moving /source/synced_imgs to /destination should produce /destination/synced_imgs. Explicitly passing /destination/synced_imgs tells PowerShell that the existing folder is the destination container, so the source folder becomes a child of it. If the goal is to merge directory contents recursively, Move-Item alone is not a full directory-merge operation. You need to enumerate the files, recreate their relative directories under the destination, and then move each file. A copy or synchronization tool can also be more suitable when preserving an entire tree.
Reply to this answer
QuietHarbor8
The issue is that the destination is being built as "$DestinationPath/$($_.Name)". When that path already exists as a directory, Move-Item interprets it as the directory that should contain the item, so the source folder is placed inside it. If you want to move each item from the source directly into the destination, pass the destination directory itself: Move-Item -Path $_ -Destination $DestinationPath -Force Also make sure $DestinationPath is the parent directory where the items should land, not the path of the existing same-named folder. The -Force parameter allows overwriting or creating items where supported; it does not merge two directories.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions