34

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?

1
  • 8
    You are doing nothing stupid, copy-item is just a PITA.
    – StingyJack
    Jan 8, 2018 at 1:24

3 Answers 3

44

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

4
  • 5
    Note 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
    Oct 29, 2019 at 15:24
  • 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). Jan 9, 2020 at 4:58
  • 2
    See also comment on SO. Jan 9, 2020 at 5:07
  • I had . and it still didn't copy the subfolders. Changing to just * fixed this issue.
    – John Dyer
    Apr 21, 2021 at 14:36
1

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
1
  • -File seems to not be a valid parameter any more. Oct 24, 2020 at 18:34
0

Setting -Container:$false will omit the directory structure:

Copy-Item -Path C:\temp\tree -Filter *.txt -Recurse -Container:$false

Docs: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-7.1#example-12--recursively-copy-files-from-a-folder-tree-into-the-current-folder

1
  • If you using this for a folder it also skips hidden folders
    – John
    May 3, 2022 at 14:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.