Home > other >  Copy only specific subdirectories and their contents to another directory
Copy only specific subdirectories and their contents to another directory

Time:09-14

In the project directory structure attached below, I am attempting to copy only the subdirectories for January, i.e. Product1_2022-01 and Product2_2022-01, including the files contained within them, to the 2022-01 folder located in the Archive. However, although the subdirectories (and contents) are copied as desired, the February files in the Product1 and Product2 directories one level up, i.e. files fileA-02 and fileB-02, are also copied.

Is it possible to copy only the subdirectories and their contents? I have included the code to reproduce the above scenario. I am new to PowerShell, so any help or advice would be greatly appreciated, thank you.

Directory structure

Code:

$source = @("C:\Product\Testing\Tested\Product1\*",
            "C:\Product\Testing\Tested\Product2\*"
           )
$destination = "C:\Archive\2022\2022-01"

Copy-Item -Path $source -Destination $destination -Recurse

CodePudding user response:

You're explicitly telling it to copy the entire contents of Product1\*, and Product2\*. If you're looking to narrow it down to just the the subfolders either specify the whole path (Product1\Product1_2022_01), or just part of the path (Product1\Product*):

$source = @("C:\Product\Testing\Tested\Product1\Product*",
            "C:\Product\Testing\Tested\Product2\Product*"
           )
$destination = "C:\Archive\2022\2022-01"

Copy-Item -Path $source -Destination $destination -Recurse
  • Related