Posted On January 4, 2020

PowerShell: Comparing 2 Directories

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Comparing 2 Directories
# Set source and destination
$source="C:\temp"
$destination="C:\tempcopy"

# Mirror the 2 directories
robocopy $source $destination /MIR /R:0 /NP

# create a test file in source to simulate a difference
$fileName = "testFile-"+(Get-Date).tostring("dd-MM-yyyy")
New-Item -itemType File -Path $source -Name ($fileName + ".txt")

# Collect child items of the 2 directories
$sourceItems=Get-ChildItem $source -Recurse -Force
$destinationItems=Get-ChildItem $destination -Recurse -Force

# Compare the 2 directories using the super slow SHA256 encryption algorithm (please don't run this on 1 million files as that take forever)
$sourceHashes=$sourceItems|% {Get-FileHash -Path $_.FullName}
$destinationHashes=$destinationItems|% {Get-FileHash -Path $_.FullName}
$fileDifferences=(Compare-Object -ReferenceObject $sourceHashes -DifferenceObject $destinationHashes -Property hash -PassThru).Path|Out-String

# Output the differences
write-host $fileDifferences

Sample Result:

PS C:\Windows\system32> $fileDifferences
C:\tempcopy\helloworld - Copy.py
C:\tempcopy\helloworld.py
C:\temp\helloworld.pp

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Time Stamp Variable

This is useful in almost any script as it enables the accurate timestamp of log…

ARP MAC to IP Resolution

If entry already exists on the ARP table:arp -a | find "XX-XX-XX-XX-XX-XX"If entry does not…

JavaScript: Show the Local Weather

Demo: https://blog.kimconnect.com/wp-content/projects/showLocalWeather.html HTML Code: <html><body><h3 class="text-center">A Free Code Camp JavaScript Intermediate Level Project</h3><div class="container"><div class="text-center">…