PowerShell: How to Copy Files from Subfolders to One Folder


Often you may want to use the Copy-Item cmdlet in PowerShell to copy files from all subfolders in a particular directory to a new directory.

You can use the following syntax to do so:

$source = "c:\users\bobbi\data3"
$dest = "c:\users\bobbi\data4"

Get-ChildItem -Path $source -Recurse -File | Copy-Item -Destination $dest

This particular example copies all of the files from all subfolders in the data3 directory into the data4 directory.

Note that all of the original files in the data3 directory will still remain there.

The following example shows how to use this syntax in practice.

Example: How to Copy Files from Subfolders to One Folder in PowerShell

Suppose that we have a directory located at the following path:

  • c:\users\bobbi\data3

We can use the following syntax to list out all folders, subfolders and files in this directory:

$source = "c:\users\bobbi\data3"

Dir $source -Recurse

The following screenshot shows how to use this syntax in practice:

We can see that this directory has the following structure:

  • c:\users\bobbi\data3\current_basketball
    • basketball_data.csv
    • basketball_data2.csv
  • c:\users\bobbi\data3\current_soccer
    • coaches.csv
    • managers.csv
    • players.csv

We can see that there are a total of five individual files in the directory.

Suppose that we would like to copy all of these individual files into a new directory.

We can use the following syntax to do so:

$source = "c:\users\bobbi\data3"
$dest = "c:\users\bobbi\data4"

Get-ChildItem -Path $source -Recurse -File | Copy-Item -Destination $dest

The following screenshot shows how to use this syntax in practice:

PowerShell copy files from subfolders to one folder

We can see that we’re able to successfully copy all files from the subfolders in the data3 directory into one folder in the data4 directory.

Note: If you would like to move all of the individual files instead of copy them, then you can use Move-Item instead of Copy-Item.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Copy and Rename a File
PowerShell: How to Use Copy-Item and Create New Directory
PowerShell: How to Use Copy-Item and Exclude Folders

Leave a Reply