question

sebastianj81-5242 avatar image
0 Votes"
sebastianj81-5242 asked sebastianj81-5242 commented

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

Regards,
Sebastian

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

MotoX80 avatar image
0 Votes"
MotoX80 answered sebastianj81-5242 commented

You are missing a backslash in the path.

A common problem that I see on these forums is that folks who are new to PS string together multiple cmdlets in one long pipeline and don't understand what it's doing when they don't get the results that they expect. While pipelines are great, if you are starting out, be verbose so that you can understand more about the object that you are dealing with. Like this.


 ForEach ($Drive in Get-PSDrive -PSProvider FileSystem) {
     $Path = $Drive.Name + ‘:\$RECYCLE.BIN’
     "Testing {0}" -f $path
     $files = Get-ChildItem $Path -Force -Recurse -ErrorAction SilentlyContinue 
     foreach ($f in $files) {
         "{0} - {1}" -f $f.name, $f.lastwritetime
         if ( $f.LastWriteTime -lt (Get-Date).AddDays(-7)) {
             "   Delete the above file."
             $f | Remove-Item -Recurse -Force -whatif 
         }
     }
 }



· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello MotoX80,

I think you don't understand what I was asking about.

Script is working and I can remove files which were modified earlier then 30 days ago. But I don't need this.

I need to remove for Recycle Bin files which were remove 30 days ago or earlier(are in Recycle Bin for 30 days or longer).

Regards,
Sebastian

0 Votes 0 ·

Thank you for help. I will try this and let you know.

0 Votes 0 ·