Delete old files in recycle bin with powershell

Dead_Jester picture Dead_Jester · Apr 2, 2014 · Viewed 25.1k times · Source

Ok, I have a script I am writing in powershell that will delete old files in the recycle bin. I want it to delete all files from the recycle bin that were deleted more than 2 days ago. I have done lots of research on this and have not found a suitable answer.

This is what I have so far(found the script online, i don't know much powershell):

$Path = 'C' + ':\$Recycle.Bin'
Get-ChildItem $Path -Force -Recurse -ErrorAction SilentlyContinue |
#Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-3) } |
Remove-Item -Recurse -exclude *.ini -ErrorAction SilentlyContinue

It is working great with one exception, it checks the file parameter "LastWriteTime". That is awesome if the user deletes the file they same day they modify it. Otherwise it fails.

How can I modify this code so that it will check when the file was deleted, not when it was written.

-On a side note, if I run this script from an administrator account on Microsoft Server 2008 will it work for all users recycle bins or just mine?


Answer:

the code that worked for me is:

$Shell = New-Object -ComObject Shell.Application
$Global:Recycler = $Shell.NameSpace(0xa)

foreach($item in $Recycler.Items())
{
    $DeletedDate = $Recycler.GetDetailsOf($item,2) -replace "\u200f|\u200e",""
    $dtDeletedDate = get-date $DeletedDate 
    If($dtDeletedDate -lt (Get-Date).AddDays(-3))
    {
        Remove-Item -Path $item.Path -Confirm:$false -Force -Recurse
    }#EndIF
}#EndForeach item

It works awesome for me, however 2 questions remain...How do I do this with multiple drives? and Will this apply to all users or just me?

Answer

N P picture N P · Oct 9, 2016

WMF 5 includes the new "Clear-RecycleBin" cmdlet.

PS > Clear-RecycleBin -DriveLetter C:\