Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- Identifie duplicate files in a comparison folder based on the contents of a source folder.
- .DESCRIPTION
- This script calculates the hash values of files in a source folder and compares them against the files in a comparison folder.
- If duplicates are found, it optionally renames the duplicate files in the comparison folder by prepending "Duplicate-" to their filenames.
- .PARAMETER SourceFolder
- The path to the source folder containing the original files.
- .PARAMETER ComparisonFolder
- The path to the comparison folder where duplicate files will be identified.
- .PARAMETER RenameDuplicates
- An optional switch parameter. If specified, the script renames duplicate files in the comparison folder by prepending "Duplicate-" to their filenames.
- .EXAMPLE
- .\Find-DuplicateFiles.ps1 -SourceFolder "C:\path\to\source\folder" -ComparisonFolder "C:\path\to\compare\folder"
- This command will identify duplicate files in the "C:\path\to\backup" folder based on the files in the "C:\path\to\main" folder.
- .EXAMPLE
- .\Find-DuplicateFiles.ps1 -SourceFolder "C:\path\to\source\folder" -ComparisonFolder "C:\path\to\compare\folder" -RenameDuplicates
- This command will identify and rename duplicate files in the "C:\path\to\compare\folder" folder by prepending "Duplicate-" to their filenames based on the files in the "C:\path\to\main" folder.
- .NOTES
- Date: 2024-05-26
- #>
- param (
- [Parameter(Mandatory = $true)]
- [string]$SourceFolder, # Main folder
- [Parameter(Mandatory = $true)]
- [string]$ComparisonFolder, # Backup folder
- [Parameter(Mandatory = $false)]
- [switch]$RenameDuplicates # Optional switch to rename duplicates
- )
- # Function to calculate the hash of a file
- function Get-CustomFileHash {
- param (
- [string]$filePath
- )
- $hash = Get-FileHash -Algorithm MD5 -Path $filePath
- return $hash.Hash
- }
- $sourceFiles = Get-ChildItem -Path $SourceFolder -File
- $comparisonFiles = Get-ChildItem -Path $ComparisonFolder -File
- $sourceFileHashes = @{}
- foreach ($file in $sourceFiles) {
- $hash = Get-CustomFileHash -filePath $file.FullName
- $sourceFileHashes[$hash] = $file.FullName
- }
- $duplicateFiles = @()
- $index = 1
- foreach ($file in $comparisonFiles) {
- $hash = Get-CustomFileHash -filePath $file.FullName
- if ($sourceFileHashes.ContainsKey($hash)) {
- $newFileName = $null
- if ($RenameDuplicates) {
- $newFileName = Join-Path -Path $ComparisonFolder -ChildPath ("Duplicate-" + $file.Name)
- Rename-Item -Path $file.FullName -NewName $newFileName
- }
- $duplicateFiles += [PSCustomObject]@{
- Number = $index
- ComparisonFile = $file.FullName
- SourceFile = $sourceFileHashes[$hash]
- RenamedTo = $newFileName
- }
- $index++
- }
- }
- $duplicateFiles | Format-Table -AutoSize
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement