[英]Recursively copy contents of directory and subdirectories in powershell
What specific syntax must be used to maintain subdirectory structure while recursively copying the contents of one directory to another directory in powershell?在将一个目录的内容递归复制到 powershell 中的另一个目录时,必须使用什么特定语法来维护子目录结构?
The following command fails to retain the subdirectory structure:以下命令未能保留子目录结构:
Get-ChildItem -Path "sourcefoldername" -Recurse | Copy-Item -Destination "C:\\Users\\username\\destinationfoldername\\"
Specifically, files located in sourcefoldername\\subdirectory
get moved by the above command into the sourcefoldername
directory.具体来说,位于sourcefoldername\\subdirectory
的文件被上述命令移动到sourcefoldername
目录中。 For example, if a source file is located at sourcefoldername\\subdirectory\\somefile.txt
, the above code makes the mistake of moving the file to C:\\Users\\username\\destinationfoldername\\somefile.txt
instead of correctly moving the file to C:\\Users\\username\\destinationfoldername\\subdirectory\\somefile.txt
.例如,如果源文件位于sourcefoldername\\subdirectory\\somefile.txt
,则上述代码会错误地将文件移动到C:\\Users\\username\\destinationfoldername\\somefile.txt
而不是正确将文件移动到C:\\Users\\username\\destinationfoldername\\subdirectory\\somefile.txt
。
The correct result must move only the contents of sourcefoldername
and not sourcefoldername
itself, but must also retain the structure of the subdirectories, with all files remaining in the appropriate subdirectories instead of being moved up to the parent directory as the above code does.正确的结果必须只移动sourcefoldername
的内容而不是sourcefoldername
本身,但还必须保留子目录的结构,所有文件都保留在适当的子目录中,而不是像上面的代码那样向上移动到父目录。
Other examples we have found on the web have either erroneously copied the sourcefoldername
itself, or have collapsed the contents as above, or have focused on only certain subdirectories, etc.我们在sourcefoldername
上发现的其他示例要么错误地复制了源文件夹名本身,要么像上面那样折叠了内容,或者只关注某些子目录等。
Don't use -Recurse
on Get-ChildItem
, instead use it on Copy-Item
.不要在Get-ChildItem
上使用-Recurse
,而是在Copy-Item
上使用它。 To solve the problem you can get the files and folders one level down then use a delay-bind scriptblock to set their destination based on their name.要解决此问题,您可以将文件和文件夹向下一层,然后使用延迟绑定脚本块根据其名称设置其目的地。
This example assumes that the destination folder already exists and it's absolute path is stored in the $destination
variable.此示例假定目标文件夹已经存在,并且它的绝对路径存储在$destination
变量中。
$destination = 'path\to\destination'
Get-ChildItem path\to\source | Copy-Item -Destination {
Join-Path $destination -ChildPath $_.Name
} -Recurse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.