PowerShell Script to Find Duplicate Files and Delete Them


Powershell:
function Get-DuplicateFile
{
    param
    (
        [Parameter (Mandatory = $true)]
        [string]$Path,
        [Parameter (Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Filter = '*.*'
    )

    begin
    {
    }
    process
    {
        if (Test-Path -Path $Path)
        {
            Get-ChildItem -Path $Path -Filter $Filter -Force -Recurse -File -ErrorAction SilentlyContinue |
            Group-Object -Property @('Length') | Where-Object { $_.Count -gt 1 } |
            ForEach-Object {
                $_.Group | Get-FileHash | Group-Object -Property @('Hash') | Where-Object { $_.Count -gt 1 }
            }
        }
    }
    end
    {
    }
}
 

My Computer My Computer

At a glance

Windows 11 Enterprise 25H2
OS
Windows 11 Enterprise 25H2
Powershell:
function Get-DuplicateFile
{
    param
    (
        [Parameter (Mandatory = $true)]
        [string]$Path,
        [Parameter (Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Filter = '*.*'
    )

    begin
    {
    }
    process
    {
        if (Test-Path -Path $Path)
        {
            Get-ChildItem -Path $Path -Filter $Filter -Force -Recurse -File -ErrorAction SilentlyContinue |
            Group-Object -Property @('Length') | Where-Object { $_.Count -gt 1 } |
            ForEach-Object {
                $_.Group | Get-FileHash | Group-Object -Property @('Hash') | Where-Object { $_.Count -gt 1 }
            }
        }
    }
    end
    {
    }
}
Thank you, but i keep it how it's and free PowerShell script, i'm not go over it again with coding.
 

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1
@FreeBooter

You don't need to be so defensive. I was not objecting to your script, I was making the point that deleting duplicates might affect a program that needed that file, in that location. I don't expect you to determine which duplicate was safe to delete.
 

My Computers My Computers

  • At a glance

    Windows 11 Pro 25H2 26200.9168AMD Ryzen 7 5825U with Radeon Graphics16GB
    OS
    Windows 11 Pro 25H2 26200.9168
    Computer type
    Laptop
    Manufacturer/Model
    Acemagic LX15PRO
    CPU
    AMD Ryzen 7 5825U with Radeon Graphics
    Motherboard
    BIOS CT_BI_AMI_LX15PRO_AB8139_A-004
    Memory
    16GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD 2TB
    Internet Speed
    30 Mbps
    Browser
    Brave
    Antivirus
    Webroot SecureAnywhere Complete beta
  • At a glance

    Windows 11 Pro 23H2 22631.2506Atom N450 1.66GHz2GB
    Operating System
    Windows 11 Pro 23H2 22631.2506
    Computer type
    Laptop
    Manufacturer/Model
    HP Mini 210-1090NR PC (bought in late 2009!)
    CPU
    Atom N450 1.66GHz
    Memory
    2GB
    Browser
    Brave
    Antivirus
    Webroot
  • Acer Swift SF114-34 laptop
    OS Windows 11 Pro 26200.8894
    CPU Pentium Silver N6000
    RAM 4GB
    BIOS v1.17
    SSD Samsung 970 EVO Plus SSD 2TB (an upgrade)
@FreeBooter

You don't need to be so defensive. I was not objecting to your script, I was making the point that deleting duplicates might affect a program that needed that file, in that location. I don't expect you to determine which duplicate was safe to delete.
Problem is i think the script works the way i wanted, i did not code a PowerShell script that i did not test multiple times to see if It's safe to use.
 

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1
@FreeBooter

I ran your modified script on C:\users\admin and it found some duplicates. But it asked if I wanted to delete them!

"Are you sure you want to delete the files in C:\Users\Admin directory? (Y/N):"

Had I said yes, would it have deleted all of them? I mean both copies?
 

My Computers My Computers

  • At a glance

    Windows 11 Pro 25H2 26200.9168AMD Ryzen 7 5825U with Radeon Graphics16GB
    OS
    Windows 11 Pro 25H2 26200.9168
    Computer type
    Laptop
    Manufacturer/Model
    Acemagic LX15PRO
    CPU
    AMD Ryzen 7 5825U with Radeon Graphics
    Motherboard
    BIOS CT_BI_AMI_LX15PRO_AB8139_A-004
    Memory
    16GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD 2TB
    Internet Speed
    30 Mbps
    Browser
    Brave
    Antivirus
    Webroot SecureAnywhere Complete beta
  • At a glance

    Windows 11 Pro 23H2 22631.2506Atom N450 1.66GHz2GB
    Operating System
    Windows 11 Pro 23H2 22631.2506
    Computer type
    Laptop
    Manufacturer/Model
    HP Mini 210-1090NR PC (bought in late 2009!)
    CPU
    Atom N450 1.66GHz
    Memory
    2GB
    Browser
    Brave
    Antivirus
    Webroot
  • Acer Swift SF114-34 laptop
    OS Windows 11 Pro 26200.8894
    CPU Pentium Silver N6000
    RAM 4GB
    BIOS v1.17
    SSD Samsung 970 EVO Plus SSD 2TB (an upgrade)
It asks you to keep the file by given its number and that file is not deleted, other one will be deleted.
 

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1
You're probably already annoyed with me, but here's a bug... it doesn't handle certain characters in the file path:

Code:
D:\source\ParseErrorCode\[MS-ERREF].pdf
The property 'Hash' cannot be found on this object. Verify that the property exists.
At D:\FreeBooter-Duplicate-Script.ps1:26 char:9
+     if ($fileHashes.ContainsKey($fileHash.Hash))
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

Using the -LiteralPath parameter should help with this.

Powershell:
    # $fileHash = Get-FileHash -Path $file.FullName -Algorithm MD5
    # becomes....
    $fileHash = Get-FileHash -LiteralPath $file.FullName -Algorithm MD5
 

My Computer My Computer

At a glance

Windows 11 Enterprise 25H2
OS
Windows 11 Enterprise 25H2
You're probably already annoyed with me, but here's a bug... it doesn't handle certain characters in the file path:

Code:
D:\source\ParseErrorCode\[MS-ERREF].pdf
The property 'Hash' cannot be found on this object. Verify that the property exists.
At D:\FreeBooter-Duplicate-Script.ps1:26 char:9
+     if ($fileHashes.ContainsKey($fileHash.Hash))
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

Using the -LiteralPath parameter should help with this.

Powershell:
    # $fileHash = Get-FileHash -Path $file.FullName -Algorithm MD5
    # becomes....
    $fileHash = Get-FileHash -LiteralPath $file.FullName -Algorithm MD5
Thank you, i have added the -LiteralPath parameter.

Powershell:
# PowerShell Script to Find Duplicate Files and Delete Them in Folder

    
    while ($true)
    {
        Write-Output ""
        $path = Read-Host "Please Enter a Directory Path to Scan"
        $path = $path -replace '"', ""
        
        
        if (Test-Path $path)
        {
            Write-Host "Valid directory path: $path"
            break
        }
        else
        {
            Write-Host "Invalid directory path, please try again."
        }
    }
    
    
    Clear-Host
    
    Write-Output "Scanning Directory: $path"
    

# Define the directory to scan
    $directoryPath = $path
    
    # Get all files in the directory
    $files = Get-ChildItem -Recurse -Path $directoryPath -File
    
    # Create a hash table to store file hashes
    $fileHashes = @{ }
    
    # Variable to track if duplicates are found
    $duplicatesFound = $false
    
    # Iterate through each file in the directory
    foreach ($file in $files)
    {
        # Compute the hash of the file
        $fileHash = Get-FileHash -LiteralPath $file.FullName -Algorithm MD5
        
        # Check if the hash already exists in the hash table
        if ($fileHashes.ContainsKey($fileHash.Hash))
        {
            Write-Output ""
            # Duplicate found
            Write-Host "Duplicate found: $($file.FullName)"
            $duplicatesFound = $true
            Write-Output ""
        }
        else
        {
            # Add the hash to the hash table
            $fileHashes[$fileHash.Hash] = $file.FullName
        }
    }
    
    # Notify the user if no duplicates were found
    if (-not $duplicatesFound)
    {
        Clear-Host
        Write-Output ""
        Write-Host "No duplicates found in the ""$directoryPath"" directory."
        Write-Output ""
        Exit
        
        
    }

    
    
    # Prompt the user for confirmation
    $confirmation = Read-Host "Are you sure you want to delete the files in $path directory? (Y/N)"
    
    if ($confirmation -eq 'Y' -or $confirmation -eq 'y')
    {
        Clear-Host
        # Define the directory to search for duplicate files
        $directory = $path
        
        # Get all files in the directory and subdirectories
        $files = Get-ChildItem -Path $directory -Recurse -File
        
        # Group files by their hash value
        $duplicates = $files | Group-Object -Property { (Get-FileHash $_.FullName).Hash } | Where-Object { $_.Count -gt 1 }
        
        
        foreach ($group in $duplicates)
        {
            #define an empty array to be used as a menu
            $menu = @()
            foreach ($file in $group.Group){
                #fill the menu array with the files in this group
                $menu+=$file
            }
            #write the custom menu
            write-host "========================"
            for ($i=0;$i -lt $menu.Length; $i++){
                write-host $($i + 1) - $menu[$i]
            }
            $answer = read-host "Please use a number to select a file to keep: "

            #Check if the user supplied a valid number.  There could be some error checking here as it just checks
            #that the user supplied a number greater than 0 and less than the length + 1 because humans don't count from 0
            #It will just exit if the user submits something other than a valid number
            if (($answer -le $($menu.Length + 1)) -and ($answer -gt 0)){
                #remove the selected file from the array
                $menu[$($answer-1)] = $null
                foreach ($file in $menu){
                    #delete the files silentlycontinue because there will probably be an error from trying to delete $null
                Remove-Item -Path $menu.FullName -ErrorAction SilentlyContinue -Force
                
                }
            }

            
        }
        
        
    }
 

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1
Guys i must say i'm not PowerShell scripting expert, i just learned it.
 

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1
I salute your efforts, sir. I hope my suggestions came off as constructive critique, not criticism. (that was a lot of Cs in a row)
 

My Computer My Computer

At a glance

Windows 11 Enterprise 25H2
OS
Windows 11 Enterprise 25H2
It asks you to keep the file by given its number and that file is not deleted, other one will be deleted.
The modified script does not ask.
 

My Computers My Computers

  • At a glance

    Windows 11 Pro 25H2 26200.9168AMD Ryzen 7 5825U with Radeon Graphics16GB
    OS
    Windows 11 Pro 25H2 26200.9168
    Computer type
    Laptop
    Manufacturer/Model
    Acemagic LX15PRO
    CPU
    AMD Ryzen 7 5825U with Radeon Graphics
    Motherboard
    BIOS CT_BI_AMI_LX15PRO_AB8139_A-004
    Memory
    16GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD 2TB
    Internet Speed
    30 Mbps
    Browser
    Brave
    Antivirus
    Webroot SecureAnywhere Complete beta
  • At a glance

    Windows 11 Pro 23H2 22631.2506Atom N450 1.66GHz2GB
    Operating System
    Windows 11 Pro 23H2 22631.2506
    Computer type
    Laptop
    Manufacturer/Model
    HP Mini 210-1090NR PC (bought in late 2009!)
    CPU
    Atom N450 1.66GHz
    Memory
    2GB
    Browser
    Brave
    Antivirus
    Webroot
  • Acer Swift SF114-34 laptop
    OS Windows 11 Pro 26200.8894
    CPU Pentium Silver N6000
    RAM 4GB
    BIOS v1.17
    SSD Samsung 970 EVO Plus SSD 2TB (an upgrade)
I salute your efforts, sir. I hope my suggestions came off as constructive critique, not criticism. (that was a lot of Cs in a row)
Thank you!
 

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1
@FreeBooter

I have just tested your modified script. It identifies dozens of duplicates but only asks about three. Even then, the option is to delete one of them.

========================
1 - Pizza oven size.txt
2 - Satellite dish.txt
3 - Things to keep handy on moving day.txt
Please use a number to select a file to keep: :


But these files are not duplicates!

Please test your scripts before publishing.
 

My Computers My Computers

  • At a glance

    Windows 11 Pro 25H2 26200.9168AMD Ryzen 7 5825U with Radeon Graphics16GB
    OS
    Windows 11 Pro 25H2 26200.9168
    Computer type
    Laptop
    Manufacturer/Model
    Acemagic LX15PRO
    CPU
    AMD Ryzen 7 5825U with Radeon Graphics
    Motherboard
    BIOS CT_BI_AMI_LX15PRO_AB8139_A-004
    Memory
    16GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD 2TB
    Internet Speed
    30 Mbps
    Browser
    Brave
    Antivirus
    Webroot SecureAnywhere Complete beta
  • At a glance

    Windows 11 Pro 23H2 22631.2506Atom N450 1.66GHz2GB
    Operating System
    Windows 11 Pro 23H2 22631.2506
    Computer type
    Laptop
    Manufacturer/Model
    HP Mini 210-1090NR PC (bought in late 2009!)
    CPU
    Atom N450 1.66GHz
    Memory
    2GB
    Browser
    Brave
    Antivirus
    Webroot
  • Acer Swift SF114-34 laptop
    OS Windows 11 Pro 26200.8894
    CPU Pentium Silver N6000
    RAM 4GB
    BIOS v1.17
    SSD Samsung 970 EVO Plus SSD 2TB (an upgrade)
@FreeBooter

I have just tested your modified script. It identifies dozens of duplicates but only asks about three. Even then, the option is to delete one of them.

========================
1 - Pizza oven size.txt
2 - Satellite dish.txt
3 - Things to keep handy on moving day.txt
Please use a number to select a file to keep: :


But these files are not duplicates!

Please test your scripts before publishing.
I selected '1' and it deleted both of the other files and they are not in the recycle bin.

Your script is seriously flawed.
 

My Computers My Computers

  • At a glance

    Windows 11 Pro 25H2 26200.9168AMD Ryzen 7 5825U with Radeon Graphics16GB
    OS
    Windows 11 Pro 25H2 26200.9168
    Computer type
    Laptop
    Manufacturer/Model
    Acemagic LX15PRO
    CPU
    AMD Ryzen 7 5825U with Radeon Graphics
    Motherboard
    BIOS CT_BI_AMI_LX15PRO_AB8139_A-004
    Memory
    16GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD 2TB
    Internet Speed
    30 Mbps
    Browser
    Brave
    Antivirus
    Webroot SecureAnywhere Complete beta
  • At a glance

    Windows 11 Pro 23H2 22631.2506Atom N450 1.66GHz2GB
    Operating System
    Windows 11 Pro 23H2 22631.2506
    Computer type
    Laptop
    Manufacturer/Model
    HP Mini 210-1090NR PC (bought in late 2009!)
    CPU
    Atom N450 1.66GHz
    Memory
    2GB
    Browser
    Brave
    Antivirus
    Webroot
  • Acer Swift SF114-34 laptop
    OS Windows 11 Pro 26200.8894
    CPU Pentium Silver N6000
    RAM 4GB
    BIOS v1.17
    SSD Samsung 970 EVO Plus SSD 2TB (an upgrade)
This is one of the only things I like about CCleaner is the duplicate file finder. I much prefer having the interface. Less room for error.
The few times I wanted to find duplicate files I used a program called dupeGuru. I never tried doing it with CCleaner. In fact I no longer have CCleaner installed. It's been so long ago I forget why. In fact it was back in 2015 when I last downloaded it. I still have the Pro install file.
 

My Computers My Computers

  • At a glance

    Windows 11 Pro 25H2Intel Core i7-10700K16GB (8GB PC4-19200 DDR4 SDRAM x2)NVIDIA GeForce GTX 1050 TI
    OS
    Windows 11 Pro 25H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    PowerSpec B746
    CPU
    Intel Core i7-10700K
    Motherboard
    ASRock Z490 Phantom Gaming 4/ax
    Memory
    16GB (8GB PC4-19200 DDR4 SDRAM x2)
    Graphics Card(s)
    NVIDIA GeForce GTX 1050 TI
    Sound Card
    Realtek Audio
    Monitor(s) Displays
    #1. LG ULTRAWIDE 34" #2. AOC Q32G2WG3 32"
    Screen Resolution
    #1. 3440 X 1440 #2. 1920 x 1080
    Hard Drives
    NVMe WDC WDS100T2B0C-00PXH0 1TB
    Samsung SSD 860 EVO 1TB
    PSU
    750 Watts (62.5A)
    Case
    PowerSpec/Lian Li ATX 205
    Keyboard
    Logitech K270
    Mouse
    Logitech M185
    Browser
    Microsoft Edge and Firefox
    Antivirus
    Webroot SecureAnywhere CE 26.1
  • At a glance

    Windows 11 Canary ChannelIntel Core i5-8400 CPU @ 2.80GHz16 MB DDR 4-2666
    Operating System
    Windows 11 Canary Channel
    Computer type
    PC/Desktop
    Manufacturer/Model
    PowerSpec G156
    CPU
    Intel Core i5-8400 CPU @ 2.80GHz
    Motherboard
    AsusTeK Prime B360M-A
    Memory
    16 MB DDR 4-2666
    Monitor(s) Displays
    23" Speptre HDMI 75Hz
    Screen Resolution
    1920x1080
    Hard Drives
    Samsung 970 EVO 500GB NVMe
    Keyboard
    Logitek K270
    Mouse
    Logitek M185
    Browser
    Firefox, Edge and Edge Canary
    Antivirus
    Windows Defender
Freebooter's script deletes files which have no duplicates. Beware. Happily, I did a full image before testing it.
 

My Computers My Computers

  • At a glance

    Windows 11 Pro 25H2 26200.9168AMD Ryzen 7 5825U with Radeon Graphics16GB
    OS
    Windows 11 Pro 25H2 26200.9168
    Computer type
    Laptop
    Manufacturer/Model
    Acemagic LX15PRO
    CPU
    AMD Ryzen 7 5825U with Radeon Graphics
    Motherboard
    BIOS CT_BI_AMI_LX15PRO_AB8139_A-004
    Memory
    16GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD 2TB
    Internet Speed
    30 Mbps
    Browser
    Brave
    Antivirus
    Webroot SecureAnywhere Complete beta
  • At a glance

    Windows 11 Pro 23H2 22631.2506Atom N450 1.66GHz2GB
    Operating System
    Windows 11 Pro 23H2 22631.2506
    Computer type
    Laptop
    Manufacturer/Model
    HP Mini 210-1090NR PC (bought in late 2009!)
    CPU
    Atom N450 1.66GHz
    Memory
    2GB
    Browser
    Brave
    Antivirus
    Webroot
  • Acer Swift SF114-34 laptop
    OS Windows 11 Pro 26200.8894
    CPU Pentium Silver N6000
    RAM 4GB
    BIOS v1.17
    SSD Samsung 970 EVO Plus SSD 2TB (an upgrade)
A suggestion to make this both more user friendly and just easier in general

You can pipe your file results to Out-GridView and have the selected stored in a variable. Then you simply delete all files in that array.

Powershell:
$FilesToDelete = $DuplicatesFiles | Out-GridView -OutputMode Multiple

foreach ($File in $FilesToDelete) {
    Remove-Item -LiteralPath "$($File.FullName)" -Force -ErrorAction SilentlyContinue
}
 

My Computer My Computer

At a glance

Linux Mint
OS
Linux Mint
Computer type
Laptop
Manufacturer/Model
System76 Lemur Pro
Freebooter's script deletes files which have no duplicates. Beware. Happily, I did a full image before testing it.
I don't how you have to make the script delete none duplicated files graduations you just made my script waste of time of coding.
 

My Computer My Computer

At a glance

Windows 11AMD Ryzen 7 5700GMicron Technology DDR4-3200 16GBNVIDIA GeForce RTX 3060
OS
Windows 11
Computer type
PC/Desktop
Manufacturer/Model
HP Pavilion
CPU
AMD Ryzen 7 5700G
Motherboard
Erica6
Memory
Micron Technology DDR4-3200 16GB
Graphics Card(s)
NVIDIA GeForce RTX 3060
Sound Card
Realtek ALC671
Monitor(s) Displays
Samsung SyncMaster U28E590
Screen Resolution
3840 x 2160
Hard Drives
SAMSUNG MZVLQ1T0HALB-000H1
Freebooter's script deletes files which have no duplicates. Beware. Happily, I did a full image before testing it.

I'm sure @pseymour will have something to pick at my coding ;)
Code:
while (1) {
    $Path = Read-Host "Please Enter a Directory Path to Scan"

    if (-not (Test-Path -Type Container $Path)) {
        Write-Host "Invalid directory path, please try again.`n"
    }
    else {
        break
    }
}

# Create array as type [System.Collections.ArrayList], so we can delete items from the list.

$HashList = [System.Collections.ArrayList]@(
    Get-ChildItem -LiteralPath $Path -Recurse -File | select -ExpandProperty FullName | foreach {
        Get-FileHash -LiteralPath $_ -Algorithm MD5 | select Hash,Path
    }
)

if (($HashList | Group-Object -Property Hash | Where-Object { $_.Count -gt 1 }).Count -eq 0) {
    Write-Host "No duplicate files found."
    exit 0
}

while (1) {
    $FilenameList = @{}
    $Index = 1

    foreach ($Hash in ($HashList | Group-Object -Property Hash | Where-Object { $_.Count -gt 1 })) {
        Write-Host "MD5: $($Hash.Name)"
        foreach ($File in $Hash.Group.Path) {
            Write-Host "[$Index] `"$File`""

            #  Build list of duplicated files, in numbered order
            $FilenameList[$Index] = $File
            $Index++
        }
        Write-Host ""
    }

    $Selection = Read-Host "Pick one of the files to delete, 'q' to quit"

    if ($Selection -match 'q') {
        break
    }
    else {
        # Recast $Selection as integer to avoid problems later
        $Selection = [int]$Selection
    }

    if ($Selection -lt 1 -or $Selection -ge $Index) {
        Write-Host "$Selection is not valid, or out of range"
    }
    else {
        $DeletedFile = $FilenameList[$Selection]
        Write-Host "Deleting `"$DeletedFile`"`n"
        Remove-Item $DeletedFile -Force

        # Remove matching file from $HashList & $FilenameList arrays
        $HashList = ($HashList | where { $_.Path -notmatch [regex]::Escape($DeletedFile) })
        $FilenameList.Remove($Selection)
    }

    if ($FilenameList.Count -eq 1) {
        break
    }
}
 

My Computer My Computer

At a glance

Windows 7
OS
Windows 7

Latest Support Threads

Back
Top Bottom