Daily Archives: February 11, 2021

Compare two folders with Powershell

This script checks first that folders exist, then that filename are the same, and then that file Hash is the same

#$folder1 = "C:\Temp\test"
#$folder2 = "C:\Temp\test2"


if ((Test-Path -Path $folder1) -and (Test-Path -Path $folder2)) {
    echo "The folders exist"
    echo "Folder1: $folder1"
    echo "Folder2: $folder2"
    $sourceFiles = Get-ChildItem $folder1 -Recurse
    $destFiles = Get-ChildItem $folder2 -Recurse
    if (Compare-Object $sourceFiles.Name $destFiles.Name) {
        echo "The folders is not the same"
    } else {
        echo "Check of the folders show us that there have the same content - OK"
        $SourceDocs = Get-ChildItem –Path $folder1 -Recurse | foreach  {Get-FileHash –Path $_.FullName}
        $DestDocs = Get-ChildItem –Path $folder2 -Recurse | foreach  {Get-FileHash –Path $_.FullName}
        if ($SourceDocs.Hash -ne $destDocs.Hash) {
            echo "There are difference in the the files"
            echo "folder1 Hash: $SourceDocs.hash"
            echo "folder2 Hash: $DestDocs.hash"
        } else  {
            echo "The folders are the same!"
        }
    }
} else {
    Echo "One of the folders or both, dosn't exist"
}