In continuation from my previous post here: Comparing folders and content with PowerShell
...I'm attempting to compare two directories that contain sub-folders (at least 4 levels deep). The second folder (folder2) contains new and updated files that I want to copy to a third folder (folder3). So far my script isn't quite working as expected. First problem, the sub-folders in folder2 need to be created in folder3. What is the best way to do this? Also, not all files (new or updated) are getting copied to folder3 from folder2.
Anyway, here is my script:
$Folder1 = "D:\folder1"
$Folder2 = "D:\folder2"
$Folder3 = "D:\folder3"
function Get-Directories ($path)
{
$PathLength = $path.length
gci $path -rec | % {
Add-Member -InputObject $_ -MemberType NoteProperty -Name RelativePath -Value $_.FullName.substring($PathLength+1)
$_
}
}
Compare-Object (Get-Directories $Folder1) (Get-Directories $Folder2) -prop RelativePath, Name, Length |
Sort RelativePath, Name, Length -desc | % {
if ($file -ne $_.RelativePath)
{ $_ }
$file = $_.RelativePath
} | Where-Object {$_.SideIndicator -eq "=>"} | ForEach-Object {Copy-Item ("$Folder2\" + $file) -Destination ("$Folder3\" + $file) -Force}