在PowerShell中递归地将一组文件从一个目录复制到另一个目录 [英] Recursively copy a set of files from one directory to another in PowerShell
问题描述
我正在尝试将所有 *.csproj.user
文件递归地从 C:\Code\Trunk
复制到 C:\Code\F2代码>.
I'm trying to copy all *.csproj.user
files recursively from C:\Code\Trunk
to C:\Code\F2
.
例如:
C:\Code\Trunk\SomeProject\Blah\Blah.csproj.user
会被复制到:
C:\Code\F2\SomeProject\Blah\Blah.csproj.user
我目前的尝试是:
Copy-Item C:\Code\Trunk -Filter *.csproj.user -DestinationC:\Code\F2 -Recurse -WhatIf
Copy-Item C:\Code\Trunk -Filter *.csproj.user -Destination C:\Code\F2 -Recurse -WhatIf
但是我得到:
如果:对目标项目"执行复制目录"操作:C:\Code\Trunk 目的地:C:\Code\F2\Trunk".
What if: Performing operation "Copy Directory" on Target "Item: C:\Code\Trunk Destination: C:\Code\F2\Trunk".
首先,它想把它们全部放在一个名为 F2\Trunk
的新文件夹中,这是错误的.其次,它没有列出任何文件.应该有大约 10 个文件要复制过来.
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!
更新:
好吧,这似乎与 C:\Code\F2
已经存在的事实有关.如果我尝试将文件复制到不存在的目的地,它会起作用.
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.
我想覆盖目标中任何现有的.csproj.user
文件.
I want to overwrite any existing .csproj.user
files in the destination.
推荐答案
以前看过这个,我不知道为什么 PowerShell 似乎无法正确处理(恕我直言).我会做的更麻烦,但它有效.
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
}
这篇关于在PowerShell中递归地将一组文件从一个目录复制到另一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!