PowerShell Copy-Item for Selective Directory Copy

~OSD~ 2,201 Reputation points
2021-01-20T00:36:24.983+00:00

Hi,

I have following directory structure:
58344-image.png

The ParentDir is located at C:\Data\ParentDir (always same path)
This ParentDir has several Sub-Directories with dynamically or randomly created names (for example DynamicDir 1, DynamicDir N).
Each DynamicDir has same folder structure (like Years, Months, Weeks, Numbers, Alphabets etc.).
When I use following PowerShell command it copies everything from source to destination (as it should be)

Copy-Item C:\Data\ParentDir -Destination E:\Storage -RECURSE -ErrorAction SilentlyContinue

But can I just copy my required directories only, for example Numbers and Year (marked with blue in screenshot) and ignore everything else?

Windows for business | Windows Server | User experience | PowerShell
Windows for business | Windows Client for IT Pros | User experience | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-01-20T03:58:06.413+00:00

    Hi,

    Does this work for you?

    $source = "C:\Data\ParentDir"  
    $destination =  "E:\Storage"  
    $includes = "Numbers","Year"  
    Get-ChildItem -Path $source -Directory -Recurse | Where-Object {$_.Name -in $includes} |   
     ForEach-Object{copy-item $_.FullName -Destination $_.FullName.Replace($source, $destination) -Recurse -ErrorAction SilentlyContinue}  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Andreas Baumgarten 123.7K Reputation points MVP Volunteer Moderator
    2021-01-20T00:48:41.177+00:00

    Maybe this is helpful (not tested!):

    $includes = "Numbers","Year"
    Get-ChildItem "C:\Data\ParentDir" -Directory -Recurse |
        Where {$_.Name -in $includes} |
        Copy-Item -Destination "E:\Storage" -Recurse -Force -ErrorAction SilentlyContinue
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    1 person found this answer helpful.
    0 comments No comments

  2. ~OSD~ 2,201 Reputation points
    2021-01-20T01:03:21.84+00:00

    Thanks for reply Andreas,

    I didn't get child directory structure (like DynamicDir 1, DynamicDir 2 etc) but only get Numbers and Year folder.
    58345-image.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.