首页 > 解决方案 > XCOPY:源文件夹是否可能包含目标文件夹?

问题描述

我想用 xcopy 复制一个文件夹。但是,只要我将目标文件夹放在源文件夹中,就不会再复制任何内容。有解决此问题的方法吗?

这个想法是将整个文件夹结构(源)的备份生成到一个子文件夹中。执行 xcopy 时,我排除了备份(目标)的子文件夹,我的备份应该存储在其中。

我已经测试了我的代码,只要目标文件夹不在源文件夹中,它就可以正常工作。

代码是用 VBA 编写的。

Function CopyFolder(ByVal sourcePath As String, ByVal destinationPath As String, ByVal excludeFile As String)
    Dim wsh As Object
    Set wsh = VBA.CreateObject("WScript.Shell")
    Dim waitOnReturn As Boolean: waitOnReturn = True
    Dim windowStyle As Integer: windowStyle = 1

    ' /e -> copys all subfolders including empty ones; /k -> retains the read-only attribute if existend
    wsh.Run "xcopy " & sourcePath & " " & destinationPath & " /e /k /exclude:" & excludeFile, vbNormalFocus, waitOnReturn
End Function

代码正在执行,没有错误,但是当我检查目标文件夹时,没有复制任何文件。

标签: vbawindowsxcopy

解决方案


这应该是不可能的,因为它应该以错误结束:“无法执行循环复制”或类似的东西。

如果你愿意,你可以做这样的事情(单线):

FOR /F "usebackq delims=;" %A IN (`dir %sourcePath% /B /AD ^|FINDSTR /V "%destinationPath%"`) DO @xcopy "%sourcePath%\%A\*.*" "%destinationPath%\" /EK

如果 SOURCE 充满了您应该在 DEST 中复制的目录。子目录及其所有文件。

注意:

 ... %A IN (**`** .... **`**)   <---- theese are reverse quotes (alt+96)

... /AD **^**|FINDSTR /V        <---- this CAP has to be written explicitly like this (but without asterisks, obvious)

 %sourcePath% and %destinationPath%     <---  This is the batch variable notation. Do your String concatenation magic here, since you're launching from inside a vba

希望这对你有帮助!:-)

再见


推荐阅读