I am trying to copy multiple files from one directory to another with PowerShell. I would like to:
- Maintain the folder/file structure.
- Copy all files within specific folders.
Hypothetical structure:
Source Folder
\User 1
\Folder 1
\Files
\Folder 2
\Files
\Folder 3
\Files
\User 2
\Folder 3
\Files
\User 3
\Folder 2
\Files
\User 4
\Folder 3
\Files
\Folder 4
\Files
Possible Scenario:
- I want to copy files where users have a Folder 1 and Folder 2.
Expected Result:
Destination Folder
\User 1
\Folder 1
\Files
\Folder 2
\Files
\User 3
\Folder 2
\Files
This is the code I have so far:
$FolderName = '\\Folder 1\\'
$source = 'C:\CDPTest\Live'
$target = 'C:\CDPTest\DevTest'
$source_regex = [regex]::Escape($source)
(gci $source -Recurse | where {-not ($_.PSIsContainer)} | select -Expand FullName) -match $FolderName |
foreach {
$file_dest = ($_ | Split-Path -Parent) -replace $source_regex, $target
if (-not (Test-Path $file_dest)) {mkdir $file_dest}
}
As you can see the match is only going to return one file path based on the current code, what I am trying to do is extend this to match several folder names.
What I have tried:
- Running this code with a different FolderName in a separate PowerShell file with no success.
- Using an array of folder names for matching.
- Using the
-and/-oroperators to extend the match function.
robocopy.robocopyyou exclude what you don't want copied, so tryrobocopy $source $target /s /xd "User 2" "User 4".$include = 'User 1', 'User 3'; ls $source | ? { $include -notcontains $_.Name }