Remove files from recycle bin for all users after 30 days

Hello All,

I’m trying to prepare powershell script which removes files from recycle bin. This script should check if files were removed 30 days ago or are in recycle bin longer and then remove them.

I found such script but I think that it is not correct as there are $_.LastWriteTime not somethink like DalateADate.

ForEach ($Drive in Get-PSDrive -PSProvider FileSystem) {
    $Path = $Drive.Name + ':\$RECYCLE.BIN'
    Get-ChildItem $Path -Force -Recurse -ErrorAction SilentlyContinue |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
	Remove-Item -Recurse -Force

I’m completly new with powershell scripting and I spent a lot of hours to find out solutions but with no luck.

May I kindly ask you to give me some adive?

OS:Windows Server 2016


Hi, welcome to the forum :wave:

This isn’t as straightforward as you might imagine. The LastWriteTime is not the date the file was added to the Recycle Bin, that’s actually the System.Recycle.DateDeleted property. To access that, you need to use a COM object.

$shell = New-Object -ComObject Shell.Application
$bin   = $shell.NameSpace(10)
$items = $bin.Items()
$items | Select-Object @{l = 'Name'; e = {$_.Name}}, @{l = 'DateDeleted'; e = {$bin.GetDetailsOf($_,2)}}

There’s a script here which looks like it should do what you want but I’ve not tested it: