Remove files from recycle bin for all users after 30 days

Sebastian Jesior 166 Reputation points
2021-05-30T11:41:14.543+00:00

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 for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 36,401 Reputation points
    2021-05-30T12:39:06.787+00:00

    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 
            }
        }
    }
    
     
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.