ConnorPyles
ConnorPyles

Reputation: 11

Copy all files with certain parent directory, while maintaining directory tree

How can I recursively copy all files within a directory structure which have the folder name "Data" in their path, while ignoring all other files?

Example:

Original directory structure

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

Copied directory structure:

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

Seems like I should be able to do something like: xcopy a*\Data* destination /s

But can't seem to get this to work.

Upvotes: 1

Views: 511

Answers (2)

Theo
Theo

Reputation: 61028

Since you tagged this PowerShell, you can do this with the code below:

$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
    }

Original structure in the parent folder:

D:\TEST
\---a
    |   sd_fks.pdf
    |
    \---b
        |   sd_fks.pdf
        |
        +---Data
        |   \---c
        |       +---d
        |       |       myFile.ext
        |       |
        |       \---e
        |               myFile2.ext
        |
        \---f
            \---g
                    myFile3.ext

Result in the destination folder:

D:\DESTINATION
\---a
    \---b
        \---Data
            \---c
                +---d
                |       myFile.ext
                |
                \---e
                        myFile2.ext

Upvotes: 0

Orel Fichman
Orel Fichman

Reputation: 160

I'm not sure why you're referring to xcopy but also tagged the question as PowerShell related but since the PowerShell answer is the one I know, the PowerShell answer is the one I'll give :)

You can use the Copy-Item cmdlet with the -Recurse argument to copy the entire directory. You can use Get-ChildItem (And also recurse, if you wish) to get the directory structure. It's a pretty nifty cmdlet. I hope this helps.

Upvotes: 0

Related Questions