Search code examples
powershellxcopy

Copy folder structure and content of specific folders


So I've found xcopy super helpful to copy entire folder structures. But I also need to copy the contents of specific folders into the new directories as well.

For example:

1. C:\OriginalDir
- \This
     * \Test
- \That
     * \Test
- \Other

I can use: xcopy C:\OriginalDir C:\TempDir /e /t to copy the entire structure of the C:\OriginalDir. However, I also need to copy the contents of both \Test folders into the new directory as well. I'm fairly new to xcopy and I've also looked into robocopy. Is there a way to do this? I'm trying to accomplish this in powershell and thought about iterating through the folder structure, but that still doesn't store the parent folder structure when I finally reach the Test folder.

Thanks.


Solution

  • Thanks to Steve for getting me started and getting me thinking about this correctly. Ended up scripting it out manually without using RoboCopy or Xcopy as I could not get them to work exactly how I wanted to.

    $target = "C:\\TestTemp"
    foreach($item in (Get-ChildItem "C:\\OriginalDir\\This" -Recurse)){
    
        if ($item.PSIsContainer -and ($item.Name -eq "obj" -or $item.Name -eq "bin")){
            $tempPath = $target
            $path = $item.FullName
            $trimmed = $path.TrimStart("C:\\OriginalDir")
            $pieces = $trimmed.Split("\\");
    
            foreach($piece in $pieces){
    
                $tempPath = "$tempPath\$piece"
                New-Item -ItemType Directory -Force -Path "$tempPath"
                if($piece -eq "Test" -or $piece -eq "Temp"){
                Copy-Item -path $path\** -Destination $tempPath -Recurse -force
                }
            }
        }
    }