Create Program/Task To Clear Recycle Bin - 2008 R2
Create Program/Task To Clear Recycle Bin - 2008 R2
Overview
This little troubleshooting guide is to help with troubled Recycle Bins on servers that have never been cleared and won't open, or take forever to open. This script will clear the Recycle Bin of files that are older than 45 days - keeping the necessary PC Charge files.
1. Copying Script Into Notepad
With the following script, copy the entire script into Notepad on the server.
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(-45) } |
Remove-Item -Recurse
}
Once you have it in Notepad, name the file ClearRecycleBin.ps1 (the extension is important here.) From the Save as type: drop down, ensure to select All Files (*.*) and then Save to the Desktop.
2. Running the File
Once you have saved the file, you can then right click on the newly created file and click Run with PowerShell. This will open up a pop up briefly while it is running and then disappear. Once it has disappeared, you can go into the Recycle Bin, sort by Date, and ensure that the oldest file is no more than 45 days old.
3. Creating a Scheduled Task
Now that we have cleared out the recycle bin of ancient files that won't be used, it will only continue to build up again unless we clear it on a normal schedule. We probably prefer not to have to login and do this each time so lets set up a scheduled task.
- General Tab
- Go to Start > Administrative Tools > Task Scheduler
- On the right click Create Task...
- Name: ClearRecycleBin
- Select: Run whether user is logged in or not
- Check: Run with highest privileges
- Configure for: Windows 7, Windows Server 2008 R2
- Triggers Tab
- Click the New... button
- Begin the task: On a schedule
- Select: Weekly
- Recur every: 1 weeks on: Sunday
- Run this at 8:00am
- Check: Stop task if it runs longer than: 1 hour
- Check: Enabled
- Actions Tab
- Click the New... button
- Action: Start a program
- Browse... to: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
- Add arguments: -NonInteractive -File "C:\Users\Administrator\Desktop\AutoEmptyRecycleBin.ps1"
- Click Ok
- Conditions Tab
- Uncheck: Start the task only if the computer is on AC power
- Check: Wake the computer to run this task
- Settings Tab
- Stop the task if it runs longer than: 1 hour
- Click Ok
- Type in the Password for the root account
- Click Ok