Have you ever found two or more files with the same name and content in different places on your computer? Duplicate files consuming space on your hard drive. They are often hard to find in person, especially when you have a lot of files and folders.
I will show you a script that automatically finds and removes duplicate files. In this script, we are looking for files that are identical in name and the original file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Define folder where script should search for duplicates $folder = 'C:\PSTesty' # Get in recurse mode all files and subfolders $files = Get-ChildItem $folder -Recurse | Where-Object {-not $_.PsIsContainer} # Group all files by name and size $groups = $files | Group-Object Name, Length # Go through every group and remove duplicates foreach ($group in $groups) { if ($group.Count -gt 1) { Write-Host "Removing filename $($group.Name) with size $($group.Length)..." $group.Group | Select-Object -Skip 1 | Remove-Item -Force } } |
Below will show steps with commands and their results. Here we can see listed files which were found in path provided at the beginning of script.
Now lets execute command which will group all files with the same name and size.
And last step will show us information about removed files.
Of course as you see this is not very advanced tool to removing duplicates but I guess it will inspire someone to build more advanced script 🙂
You helped me a lot by posting this article and I love what I’m learning.