Powershell Copy-Item recursively but don't include folder name

17

3

This is a stupid question, but I just don't know why it isn't working.

I am trying to copy the files from FolderA to FolderB recursively. I am doing this:

Copy-Item -Path "C:\FolderA\" -Destination "C:\FolderB\" -recurse -Force -Verbose

It works great, no problem.

Except the result in FolderB is this:

C:\FolderB\FolderA\file.txt

Whereas I want it to be:

C:\FolderB\file.txt

What stupid obvious thing am I missing?

CleverPatrick

Posted 2016-12-04T21:38:59.413

Reputation: 1 651

3You are doing nothing stupid, copy-item is just a PITA. – StingyJack – 2018-01-08T01:24:01.697

Answers

25

Your command is telling PowerShell to copy the folder itself, with all its contents, to the destination folder. To copy only the contents of the original folder, change your path as follows:

Copy-Item -Path "C:\FolderA\*" -Destination "C:\FolderB\" -recurse -Force -Verbose

Notice the asterisk (*) after the folder name. This will copy the content (including subfolders) of the folder, but not the folder itself to the destination folder.

Using the Copy-Item Cmdlet

FastEthernet

Posted 2016-12-04T21:38:59.413

Reputation: 3 385

2Note that this doesn't copy the folder structure if destination folder does not exist. Calling md "C:\FolderB" before Copy-Item seems to avoid this problem. – zett42 – 2019-10-29T15:24:30.000

Building on @zett42's comment above, if the destination folder does not already exist, it seems Copy-Item will reproduce the folder structure, but one level down (e.g. C:\FolderA\B\C is copied to C:\FolderB\C instead of C:\FolderB\B\C), and may also fail when multiple subfolders exist. Always ensure the destination folder exists before calling Copy-Item. This smells like a bug (I can't see any reason why this inconsistent behaviour would be desirable). – Marc Durdin – 2020-01-09T04:58:48.483

1

See also comment on SO.

– Marc Durdin – 2020-01-09T05:07:56.577

0

You can use -File -Recurse for Copy only Files Recursively:

Copy-Item -Path "C:\Source" -Destination "C:\Dest" -File -recurse -Force -Verbose

Or use -Directory -Recurse to copy only empy folder structure:

Copy-Item -Path "C:\Source" -Destination "C:\Dest" -Directory -recurse -Force -Verbose

Kind Regards,

Paul Pedroza

Paul Andres Pedroza M

Posted 2016-12-04T21:38:59.413

Reputation: 1

-1

Copy-Item -Path "C:\FolderA" -Destination "C:\FolderB" -recurse -Force -Verbose

Would also work.

Mark Gladson

Posted 2016-12-04T21:38:59.413

Reputation: 1

1This appears to be a comment on FastEthernet's similar answer. If you want to propose an alternate answer, you should explain why it answers the question. – Blackwood – 2017-11-02T14:42:28.303

That creates C:\FolderB if it does not exist - but creates C:\FolderB\FolderA if C:\FolderB does exist. If you run that command twice you can get two copies of everything in slightly different locations! So much pain. – Lamarth – 2019-12-19T03:56:20.343