【问题标题】:Copy all files with certain parent directory, while maintaining directory tree复制具有特定父目录的所有文件,同时维护目录树
【发布时间】:2020-07-22 11:18:38
【问题描述】:

如何递归复制目录结构中路径中包含文件夹名称“Data”的所有文件,同时忽略所有其他文件?

例子:

原始目录结构

                         a\b\Data\c\d\myfile2.ext
                         a\b\Data\c\e\myfile.ext
                         a\b\f\g\myfile3.ext

复制的目录结构:

                         a\b\Data\c\d\myfile.ext
                         a\b\Data\c\e\myfile2.ext

似乎我应该能够执行以下操作:xcopy a*\Data* destination /s

但似乎无法让它发挥作用。

【问题讨论】:

    标签: powershell copy xcopy


    【解决方案1】:

    既然你标记了这个PowerShell,你可以用下面的代码做到这一点:

    $sourcePath  = 'D:\Test'          # the parent directory
    $destination = 'D:\Destination'   # the directory to copy to
    
    Get-ChildItem -Path $sourcePath -Filter * -File -Recurse | 
        Where-Object { ($_.DirectoryName -split '\\') -contains 'Data' } |   # the file's path should include folder "Data"
        ForEach-Object {
            # create the path for the destination including all subfolders
            $targetPath = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourcePath.Length)
            # if that path does not yet exist create it
            if (!(Test-Path $targetPath -PathType Container)) {
                New-Item -ItemType Directory -Path $targetPath | Out-Null
            }
            $_ | Copy-Item -Destination $targetPath -Force
        }
    

    父文件夹中的原始结构:

    D:\测试 \ - -一种 | sd_fks.pdf | \---b | sd_fks.pdf | +---数据 | \ - -C | +---d | |我的文件.ext | | | \---e |我的文件2.ext | \ - -F \ - -G 我的文件3.ext

    目标文件夹中的结果:

    D:\目的地 \ - -一种 \---b \ - -数据 \ - -C +---d |我的文件.ext | \---e 我的文件2.ext

    【讨论】:

      【解决方案2】:

      我不确定您为什么要提到 xcopy,但也将该问题标记为与 PowerShell 相关,但由于 PowerShell 答案是我所知道的答案,因此 PowerShell 答案是我将给出的答案:)

      您可以使用带有 -Recurse 参数的 Copy-Item cmdlet 来复制整个目录。您可以使用 Get-ChildItem (如果您愿意,还可以使用递归)来获取目录结构。这是一个非常漂亮的 cmdlet。我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        • 2011-05-20
        • 2016-08-23
        相关资源
        最近更新 更多