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