3

i try this script to synchronize 2 folder

$Folder1Path = 'C:\test1'
$Folder2Path = 'C:\test2'
$folder1Files = Get-ChildItem -Recurse -path $Folder1Path
$folder2Files = Get-ChildItem -Recurse -path $Folder2Path
$file_Diffs = Compare-Object -ReferenceObject $folder1Files -DifferenceObject $folder2Files
$file_Diffs | foreach {
$copyParams = @{'Path' = $_.InputObject.FullName}
if($_.SideIndicator -eq '<=' )
{$copyParams.Destination = $Folder2Path}
copy-Item @copyParams -force
}

But i have a problem when the script copy the file under test2 it does not respect the correct path :

in folder test1 i have: test1\test3\test4.txt and test1\test5.txt in folder test2 i have: test2\test5.txt

when i execute my script i find in folder test2 test2\test5.txt test2\test4.txt test2\test3

h.s
  • 115
  • 3
  • 11

1 Answers1

4

You are setting your destination for Copy-Item always to 'C:\test1'. That will ignore any deeper folder structure of the source file. If you want to keep the folder structure of the source, you would need to adjust the FullName property of your file accordingly:

$Folder1Path = 'C:\test1'
$Folder2Path = 'C:\test2'
$folder1Files = Get-ChildItem -Recurse -path $Folder1Path
$folder2Files = Get-ChildItem -Recurse -path $Folder2Path
$file_Diffs = Compare-Object -ReferenceObject $folder1Files -DifferenceObject $folder2Files
$file_Diffs | 
  foreach {
     $copyParams = @{'Path' = $_.InputObject.FullName}
     if($_.SideIndicator -eq '<=' )
     { 
         $copyParams.Destination = $_.InputObject.FullName -replace [regex]::Escape($Folder1Path),$Folder2Path
     }
     copy-Item @copyParams -force
}
Manuel Batsching
  • 3,406
  • 14
  • 20