Last active
August 24, 2021 15:31
-
-
Save scottmwyant/981bdffbae8898a22a558e0c75b6cbcf to your computer and use it in GitHub Desktop.
Remove-DuplicateFiles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# ============================================================================= | |
# This script can be used to clean a folder that has 2 copies of each file. | |
# There should be an original version, ie "fileA.txt" and a copy, | |
# ie "fileA - Copy.txt". You need to review / change the values of the | |
# constants below. | |
# | |
# https://gist.github.com/scottmwyant/981bdffbae8898a22a558e0c75b6cbcf | |
# ============================================================================= | |
# | |
# Specify the target folder | |
$TARGET_FOLDER = "C:\Users\username\Downloads\test" | |
# Set the following values to either $true or $false | |
$DELETE_COPIES = $true | |
$DELETE_ORIGINALS = $false | |
$DRY_RUN = $true | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
# Define Functions | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
function Get-Name([System.IO.FileSystemInfo]$file) { | |
$nameLength = $file.Name.Length - $file.Extension.Length | |
return $file.Name.Substring(0, $nameLength) | |
} | |
function Remove-Files([System.IO.FileInfo[]] $files) { | |
$params = @{ Force = $true; WhatIf = $DRY_RUN; } | |
$files | Remove-Item @params | |
} | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
# Main script | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
# Get all files from within this folder, seperate into arrays of originals and copies | |
$allFiles = Get-ChildItem $TARGET_FOLDER | |
$originals = $allFiles | Where-Object { (Get-Name $_) -NotMatch " - Copy$"} | |
$copies = $allFiles | Where-Object { (Get-Name $_) -Match " - Copy$"} | |
# Show the files that were found to be "originals" | |
Write-Host | |
Write-Host "=== ORIGINALS ($($originals.Length)) ===" | |
Write-Host ($originals -join "`n`r") | |
Write-Host | |
# Show the files that were found to be "copies" | |
Write-Host "=== COPIES ($($copies.Length)) ===" | |
Write-Host ($copies -join "`n`r") | |
Write-Host | |
if($DELETE_ORIGINALS){ | |
Write-Host "Deleting ORINGALS (Dry-Run = $DRY_RUN)" | |
Write-Host | |
Remove-Files $originals | |
} | |
if($DELETE_COPIES){ | |
Write-Host "Deleting COPIES (Dry-Run = $DRY_RUN)" | |
Write-Host | |
Remove-Files $copies | |
} | |
Write-Host "=== Done ===" | |
Write-Host |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment