Recursively copy a set of files from one directory to another in PowerShell

Mike Christensen picture Mike Christensen · Sep 12, 2014 · Viewed 49.8k times · Source

I'm trying to copy all *.csproj.user files recursively from C:\Code\Trunk to C:\Code\F2.

For example:

C:\Code\Trunk\SomeProject\Blah\Blah.csproj.user

Would get copied to:

C:\Code\F2\SomeProject\Blah\Blah.csproj.user

My current attempt is:

Copy-Item C:\Code\Trunk -Filter *.csproj.user -Destination C:\Code\F2 -Recurse -WhatIf

However I get:

What if: Performing operation "Copy Directory" on Target "Item: C:\Code\Trunk Destination: C:\Code\F2\Trunk".

First, it wants to put them all in a new folder called F2\Trunk which is wrong. Second, it doesn't list any of the files. There should be about 10 files to be copied over.

What's the correct syntax for the command? Thanks!

Update:

Okay, it seems to have something to do with the fact that C:\Code\F2 already exists. If I try copying the files over to a destination that does not exist, it works.

I want to overwrite any existing .csproj.user files in the destination.

Answer

Jaykul picture Jaykul · Feb 23, 2017

You guys are making this hideously complicated, when it's really simple:

Copy-Item C:\Code\Trunk -Filter *.csproj.user -Destination C:\Code\F2 -Recurse

Will copy the Directory, creating a "Trunk" directory in F2. If you want to avoid creating the top-level Trunk folder, you have to stop telling PowerShell to copy it:

Get-ChildItem C:\Code\Trunk | Copy-Item -Destination C:\Code\F2 -Recurse -filter *.csproj.user