Using Powershell to recursively copy only specific subdirectories

Using Powershell to recursively copy only specific subdirectories

This code solves the following issue:
Recursively copy specific subdirectories (subfolders) into a destination path using Powershell.

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

Code was running on Windows 10 with this Powershell Version 5.1.19041.1237:

Code running on powershell
Code running on powershell

Keywords: Powershell, recursively, recursiv, copy, specific subfolder,  specific subfolders, specific subdirectories, specific subdirectory

This information can also be found on Microsoft Q&A


Dieser Code behebt folgendes Problem:

Kopiere bestimmte Unterverzeichnisse rekursiv von einem Quelleverzeichnis in ein Zielverzeichnis mit Powershell.

Diese Information kann auch auf Microsoft Q&A gefunden werden.

Stichworte: Powershell, rekursiv, kopieren, spezifisches Unterverzeichnis, spezifische Unterverzeichnisse