Reputation: 99
I'm trying to copy folders from one directory to the sub directory of another folder if the folder names match.
The starting folder structure is like this -
Data > VR-01
The entire VR-01
folder should be moved to the destination folder is like this -
Data > VR-0-1000 > VR-01 [match this name] > Archive > [matched folder (VR-01) should go here]
The VR's are separated out into different folders, 0-1000, 1001-2000, etc. with the same directory structure.
$startPath = "C:\Start\Data"
$destinationPath = "C:\Destination\Data"
$DestinationFolders = Get-ChildItem -Path $destinationPath -Directory | Select -ExpandProperty FullName
# for each item in the folder that is a directory (folder)
Get-ChildItem -Path $startPath -Recurse -Directory | %{
#Get the folder name to compare it to the destination folder
$CurrentFolderName = ($_.Name)
#Find matching directory for that folder
#Where-Object
$DestinationFolders | ?{$CurrentFolderName -like $DestinationFolders}
#Copy files
Copy-Item -Path $_.FullName -Destination $DestinationFolders -WhatIf
}
I've tried using the -match
command and it failed due to the \ character being part of the regex from what I can tell, so I switched to -like
.
It looks like I'm missing a step in comparing the folder names and copying them, because from the -WhatIf
command I see that it is just copying the folders over to the first subfolder without matching the name.
Upvotes: 2
Views: 402
Reputation: 116
How I visualise your description is that in the Destination\VR-0-1000 folder, you want to copy the source VR-01 if a VR-01 subfolder exists in VR-0-1000. There may not necesarily exist a Destination\VR-0-1000\VR-n
.
I had a stab at it. Not guaranteed for efficiency, but I believe it will do the job.
$startPath = "C:\Start\Data"
$destinationPath = "C:\Destination\Data"
$sourceNames = (Get-ChildItem $startPath -Recurse -Directory).Name
(Get-ChildItem $destinationPath -Directory).FullName | % {
# For each folder named 'VR-****-****'
Get-ChildItem -Path $_ | % {
# For each folder named VR-****-****\VR-****
if($sourceNames -Contains $_.Name)
{
$sourceFolder = "$startPath\$($_.Name)\*"
$destFolder = $_.FullName
Write-Output "Copying $sourceFolder into $destFolder"
Copy-Item -Path $sourceFolder -Destination $destFolder -Recurse
}
}
}
I ran it on a structure like so
C:.
├───Dest
│ ├───VR-1-2
│ │ └───VR-01
│ └───VR-3-4
│ └───VR-03
└───Start
├───VR-01
├───VR-02
├───VR-03
└───VR-05
Output:
Copying C:\soverflowtest\Start\VR-01\* into C:\soverflowtest\Dest\VR-1-2\VR-01
Copying C:\soverflowtest\Start\VR-03\* into C:\soverflowtest\Dest\VR-3-4\VR-03
Upvotes: 2