1
votes

Here, I'm trying to compare 2 folders and copy the difference in the third folder recursively.

Below is my code and I'm able to do most of the part, but unable to get the files copied in the exact folder structure as if in the Folder1. This script actually copy the files directly on the folder3 without any folders. This just copies the files alone from different folder and put them in the folder3. Any help is greatly appreciated.

$Folder1path = "M:\Technical\foldercompare\folder1"
$Folder2path = "M:\Technical\foldercompare\folder2"
$Folder3path = "M:\Technical\foldercompare\folder3"
$Folder1 = Get-childitem -path $Folder1path -Recurse
$Folder2 = Get-childitem -path $Folder2path -Recurse
Compare-Object -ReferenceObject $folder1 -DifferenceObject $Folder2
Compare-Object $Folder1 $Folder2 -Property Name, Length  | 
Where-Object {$_.SideIndicator -eq "<="} | 
ForEach-Object {
            Copy-Item "$Folder1path\$($_.name)" -Destination "$Folder3path" -Force -Recurse
}
1

1 Answers

0
votes

The script below represents one way you could approach the task (assuming your 3 directories share a common parent dir). As an aside, your initial attempt failed to handle the $nulls that occur when $Folder1Path or $Folder2Path are empty.

# Files in 1 but not in 2 should wind up in 3 with the same dir structure as occurs in 1
param(
    $Folder1path = "$PSScriptRoot\folder1",
    $Folder2path = "$PSScriptRoot\folder2",
    $Folder3path = "$PSScriptRoot\folder3"
)

$ErrorActionPreference = "Stop";
Set-StrictMode -Version 'Latest'

Get-ChildItem -Path $Folder1Path -Recurse | Where-Object {

    [string] $toDiff = $_.FullName.Replace($Folder1path, $Folder2path)
    # Determine what's in 2, but not 1
    [bool] $isDiff = (Test-Path -Path $toDiff) -eq $false
    
    if ($isDiff) {
        # Create destination path that contains folder structure
        $dest = $_.FullName.Replace($Folder1path, $Folder3path)
        Copy-Item -Path $_.FullName -Destination $dest -Verbose -Force
    }
}