Copy contents of all subfolders matching a certain name, while preserving folder structure using Powershell (from old thread)

Gerd Besch 1 Reputation point
2021-09-15T20:59:27.447+00:00

This is a followup on the question asked in 2012 in this thread:
copy-contents-of-all-subfolders-matching-a-certain-name-while-preserving-folder-structure

I updated this powershell script and added a line to match a list of selected directories:
Details can be found on my homepage

I just added a line to put all required subdirectories into one variable $ToMatchFoldernames.

Example: Recursively copy only subdirectories (subfolders) and files in F:\source1\ of "Bob" and "Charlie" to destination C:\dest1

Source-Directory:

F:\source1\Alice\test1.docx
F:\source1\Bob\test2.docx
F:\source1\Bob\test2a.docx
F:\source1\Charlie\test3.docx

Destination:

C:\dest1\

Based on this example from mjolinor (thank´s for that!) i added the $ToMatchFoldernames line. Just put all foldernames you want to copy in this variable seperated by "|" (ascii-code: 124) an run this code in Powershell:

$source = 'F:\source1\'
$target = 'C:\dest1\'
$ToMatchFoldernames = "\\Bob\\|\\Charlie\\"
$source_regex = [regex]::escape($source)
(gci $source -recurse | where {-not ($_.psiscontainer)} | select -expand fullname) -match $ToMatchFoldernames |
foreach {
$file_dest = ($_ | split-path -parent) -replace $source_regex,$target

if (-not (test-path $file_dest)){mkdir $file_dest}
copy-item $_ -Destination $file_dest
}

Result after copy:

C:\dest1\Bob\test2.docx
C:\dest1\Bob\test2a.docx
C:\dest1\Charlie\test3.docx

Using-Powershell-to-recursively-copy-only-specific-subdirectories-15-09-_2021.png

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,383 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 39,381 Reputation points
    2021-09-16T13:32:23.28+00:00

    Hello GerdBesch,

    Thank you for sharing with the community!!

    I would like also to suggest creating your contribution with the code in Github, which is the Microsoft recommendation after retiring the old Microsoft TechNet Gallery: https://learn.microsoft.com/en-us/teamblog/technet-gallery-retirement

    Best regards!

    0 comments No comments