Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 734
Mike Christensen Avatar asked Sep 12 '14 21:09

Mike Christensen


People also ask

How do I copy an entire folder in PowerShell?

Use Copy-Item Cmdlet to Copy Folder With Subfolders in PowerShell. The Copy-Item cmdlet copies an item from one location to another. You can use this cmdlet to copy the folder and its contents to the specified location. You will need to provide the source and destination path to copy from one place to another.

Does xcopy work in PowerShell?

xcopy is the windows command. It works with both PowerShell and cmd as well because it is a system32 utility command.

How do I use cp in PowerShell?

To copy items in PowerShell, one needs to use the Copy-Item cmdlet. When you use the Copy-Item, you need to provide the source file name and the destination file or folder name. In the below example, we will copy a single file from the D:\Temp to the D:\Temp1 location.


2 Answers

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 
like image 94
Jaykul Avatar answered Sep 20 '22 01:09

Jaykul


While the most voted answer is perfectly valid for single file types, if you need to copy multiple file types there is a more useful functionality called robocopy exactly for this purpose with simpler usage

robocopy C:\Code\Trunk C:\Code\F2 *.cs *.xaml *.csproj *.appxmanifest /s 
like image 43
user3141326 Avatar answered Sep 23 '22 01:09

user3141326