Search code examples
windowspowershellfile

Delete duplicate files in array


I have a folder with duplicate files the first 10-letters in the filename is the same and the last 2 are random, i want to remove these files via PWSH script. A specific file is located in the same folder where the duplicate files are. I Don't want to delete this specific file, i only want to delete the duplicate files older then 1 week.

EDIT: I want to delete everything older then 1 week in C:\temp\Folder except from "DontDelete", I want to save that file. (The DontDelete has duplicates as well)

$Location = "C:\temp\Folder\" # Here is where all the duplicate files are located
$W = "7" 
$Date = (Get-date).AddDays(-$W)
$DontDelete = "DontDelete*"  
$Array = Get-Content -Path @("C:\Delete\Remove.txt")

Get-ChildItem -Path $Location |
  where { $_.LastWriteTime -lt $Date } |
    Out-file "C:\Delete\Remove.txt" 

Set-Location "$Location" 
$Array 

foreach ($Item in $Array) {
    Remove-Item -Recurse -Force
}

# If $DontDelete exsist in $array (Which it will) don't delete the $Dontdelete file.
# Delete the rest of the files which are older then 7-days.


Solution

  • Im confused as to what your asking but if your asking to just not delete one file. Pipe your Get-Child into a Where-Object filter

    $Time = (Get-Date).AddDays(-7)
    $Fnd  = "/file/not/to/delete.txt"
    
    Get-ChildItem -Path $Location |
      Where-Object {$_.LastWriteTime -lt $Time -and $_.Name -ne $Fnd} |
        Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
    
    

    Then you accomplish everything you asked for in one liner. The initial Get-Child, gets all the files in your directory pipes into Where-Object which then filters all files older than a week and not your desired file. Which finally pipes into Remove-Item which deletes all the items.