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

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


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


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


Seen this before, and I don't know why PowerShell can't seem to get it right (IMHO). What I would do is more cumbersome but it works.

$Source = 'C:\Code\Trunk'$Files = '*.csproj.user'$Dest = 'C:\Code\F2'Get-ChildItem $Source -Filter $Files -Recurse | ForEach{    $Path = ($_.DirectoryName + "\") -Replace [Regex]::Escape($Source), $Dest    If(!(Test-Path $Path)){New-Item -ItemType Directory -Path $Path -Force | Out-Null    Copy-Item $_.FullName -Destination $Path -Force}