Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete old files in recycle bin with powershell

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?

like image 397
Dead_Jester Avatar asked Apr 02 '14 15:04

Dead_Jester


People also ask

How do I delete everything from my Recycle Bin?

Go to your Recycle Bin folder on your Windows system, right-click on it, and select Empty Recycle Bin. Alternately, you can open the Empty Recycle Bin, select the required files and then press the Delete key.

Can PowerShell delete files?

In PowerShell, the Remove-Item cmdlet deletes one or more items from the list. It utilizes the path of a file for the deletion process. Using the “Remove-Item” command, you can delete files, folders, variables, aliases, registry keys, etc.


2 Answers

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

PS > Clear-RecycleBin -DriveLetter C:\

like image 68
N P Avatar answered Sep 30 '22 16:09

N P


These two lines will empty all the files recycle bin:

$Recycler = (New-Object -ComObject Shell.Application).NameSpace(0xa)
$Recycler.items() | foreach { rm $_.path -force -recurse }
like image 21
cmcginty Avatar answered Sep 30 '22 16:09

cmcginty