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 Computers

System One System Two

  • OS
    Windows 11 Pro 24H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    Intel NUC12WSHi7
    CPU
    12th Gen Intel Core i7-1260P, 2100 MHz
    Motherboard
    NUC12WSBi7
    Memory
    64 GB
    Graphics Card(s)
    Intel Iris Xe
    Sound Card
    built-in Realtek HD audio
    Monitor(s) Displays
    Dell U3219Q
    Screen Resolution
    3840x2160 @ 60Hz
    Hard Drives
    Samsung SSD 990 PRO 1TB
    Keyboard
    CODE 104-Key Mechanical with Cherry MX Clears
    Antivirus
    Microsoft Defender
  • Operating System
    Linux Mint 21.2 (Cinnamon)
    Computer type
    PC/Desktop
    Manufacturer/Model
    Intel NUC8i5BEH
    CPU
    Intel Core i5-8259U CPU @ 2.30GHz
    Memory
    32 GB
    Graphics card(s)
    Iris Plus 655
    Keyboard
    CODE 104-Key Mechanical with Cherry MX Clears
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

System One

  • 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

System One System Two

  • OS
    Windows 11 Pro 24H2 26100.2894
    Computer type
    Laptop
    Manufacturer/Model
    Acer Swift SF114-34
    CPU
    Pentium Silver N6000 1.10GHz
    Memory
    4GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD
    Cooling
    fanless
    Internet Speed
    150 Mbps
    Browser
    Brave
    Antivirus
    Webroot Secure Anywhere
    Other Info
    System 3

    ASUS T100TA Transformer
    Processor Intel Atom Z3740 @ 1.33GHz
    Installed RAM 2.00 GB (1.89 GB usable)
    System type 32-bit operating system, x64-based processor

    Edition Windows 10 Home
    Version 22H2 build 19045.3570
  • 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
@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

System One

  • 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

System One System Two

  • OS
    Windows 11 Pro 24H2 26100.2894
    Computer type
    Laptop
    Manufacturer/Model
    Acer Swift SF114-34
    CPU
    Pentium Silver N6000 1.10GHz
    Memory
    4GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD
    Cooling
    fanless
    Internet Speed
    150 Mbps
    Browser
    Brave
    Antivirus
    Webroot Secure Anywhere
    Other Info
    System 3

    ASUS T100TA Transformer
    Processor Intel Atom Z3740 @ 1.33GHz
    Installed RAM 2.00 GB (1.89 GB usable)
    System type 32-bit operating system, x64-based processor

    Edition Windows 10 Home
    Version 22H2 build 19045.3570
  • 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
It asks you to keep the file by given its number and that file is not deleted, other one will be deleted.
 

My Computer

System One

  • 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 Computers

System One System Two

  • OS
    Windows 11 Pro 24H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    Intel NUC12WSHi7
    CPU
    12th Gen Intel Core i7-1260P, 2100 MHz
    Motherboard
    NUC12WSBi7
    Memory
    64 GB
    Graphics Card(s)
    Intel Iris Xe
    Sound Card
    built-in Realtek HD audio
    Monitor(s) Displays
    Dell U3219Q
    Screen Resolution
    3840x2160 @ 60Hz
    Hard Drives
    Samsung SSD 990 PRO 1TB
    Keyboard
    CODE 104-Key Mechanical with Cherry MX Clears
    Antivirus
    Microsoft Defender
  • Operating System
    Linux Mint 21.2 (Cinnamon)
    Computer type
    PC/Desktop
    Manufacturer/Model
    Intel NUC8i5BEH
    CPU
    Intel Core i5-8259U CPU @ 2.30GHz
    Memory
    32 GB
    Graphics card(s)
    Iris Plus 655
    Keyboard
    CODE 104-Key Mechanical with Cherry MX Clears
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

System One

  • 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

System One

  • 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 Computers

System One System Two

  • OS
    Windows 11 Pro 24H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    Intel NUC12WSHi7
    CPU
    12th Gen Intel Core i7-1260P, 2100 MHz
    Motherboard
    NUC12WSBi7
    Memory
    64 GB
    Graphics Card(s)
    Intel Iris Xe
    Sound Card
    built-in Realtek HD audio
    Monitor(s) Displays
    Dell U3219Q
    Screen Resolution
    3840x2160 @ 60Hz
    Hard Drives
    Samsung SSD 990 PRO 1TB
    Keyboard
    CODE 104-Key Mechanical with Cherry MX Clears
    Antivirus
    Microsoft Defender
  • Operating System
    Linux Mint 21.2 (Cinnamon)
    Computer type
    PC/Desktop
    Manufacturer/Model
    Intel NUC8i5BEH
    CPU
    Intel Core i5-8259U CPU @ 2.30GHz
    Memory
    32 GB
    Graphics card(s)
    Iris Plus 655
    Keyboard
    CODE 104-Key Mechanical with Cherry MX Clears
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

System One System Two

  • OS
    Windows 11 Pro 24H2 26100.2894
    Computer type
    Laptop
    Manufacturer/Model
    Acer Swift SF114-34
    CPU
    Pentium Silver N6000 1.10GHz
    Memory
    4GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD
    Cooling
    fanless
    Internet Speed
    150 Mbps
    Browser
    Brave
    Antivirus
    Webroot Secure Anywhere
    Other Info
    System 3

    ASUS T100TA Transformer
    Processor Intel Atom Z3740 @ 1.33GHz
    Installed RAM 2.00 GB (1.89 GB usable)
    System type 32-bit operating system, x64-based processor

    Edition Windows 10 Home
    Version 22H2 build 19045.3570
  • 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
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

System One

  • 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

System One

  • 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

System One System Two

  • OS
    Windows 11 Pro 24H2 26100.2894
    Computer type
    Laptop
    Manufacturer/Model
    Acer Swift SF114-34
    CPU
    Pentium Silver N6000 1.10GHz
    Memory
    4GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD
    Cooling
    fanless
    Internet Speed
    150 Mbps
    Browser
    Brave
    Antivirus
    Webroot Secure Anywhere
    Other Info
    System 3

    ASUS T100TA Transformer
    Processor Intel Atom Z3740 @ 1.33GHz
    Installed RAM 2.00 GB (1.89 GB usable)
    System type 32-bit operating system, x64-based processor

    Edition Windows 10 Home
    Version 22H2 build 19045.3570
  • 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
@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

System One System Two

  • OS
    Windows 11 Pro 24H2 26100.2894
    Computer type
    Laptop
    Manufacturer/Model
    Acer Swift SF114-34
    CPU
    Pentium Silver N6000 1.10GHz
    Memory
    4GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD
    Cooling
    fanless
    Internet Speed
    150 Mbps
    Browser
    Brave
    Antivirus
    Webroot Secure Anywhere
    Other Info
    System 3

    ASUS T100TA Transformer
    Processor Intel Atom Z3740 @ 1.33GHz
    Installed RAM 2.00 GB (1.89 GB usable)
    System type 32-bit operating system, x64-based processor

    Edition Windows 10 Home
    Version 22H2 build 19045.3570
  • 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
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

System One System Two

  • OS
    Windows 11 Canary Channel
    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
    Samsung SAM0A87 Samsung SAM0D32
    Screen Resolution
    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
    ESET Internet Security
  • 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-S
    Memory
    16 MB DDR 4-2666
    Monitor(s) Displays
    23" Speptre HDMI 75Hz
    Screen Resolution
    1920x1080
    Hard Drives
    Samsung 970 EVO 500GB NVMe
    Mouse
    Logitek M185
    Keyboard
    Logitek K270
    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

System One System Two

  • OS
    Windows 11 Pro 24H2 26100.2894
    Computer type
    Laptop
    Manufacturer/Model
    Acer Swift SF114-34
    CPU
    Pentium Silver N6000 1.10GHz
    Memory
    4GB
    Screen Resolution
    1920 x 1080
    Hard Drives
    SSD
    Cooling
    fanless
    Internet Speed
    150 Mbps
    Browser
    Brave
    Antivirus
    Webroot Secure Anywhere
    Other Info
    System 3

    ASUS T100TA Transformer
    Processor Intel Atom Z3740 @ 1.33GHz
    Installed RAM 2.00 GB (1.89 GB usable)
    System type 32-bit operating system, x64-based processor

    Edition Windows 10 Home
    Version 22H2 build 19045.3570
  • 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
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

System One

  • OS
    Windows 11
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

System One

  • 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

System One

  • OS
    Windows 7

Latest Support Threads

Back
Top Bottom