PowerShell

Empty the Recycle Bin with PowerShell and the Task Scheduler

In this post I will show you how to empty the recycle bin automatically. For this I will use PowerShell and Scheduled PowerShell Jobs. So I will show two ways how to do this (second one is recommended).

Option 1: Task Scheduler

The Task Scheduler is a feature in Microsoft Windows. We create a file and this file, which contains Clear-RecycleBin, is executed according to our schedule. Here is the code. Information must be entered in line 3 to 5.

### This script creates a Scheduled Task to clear the recycle bin every x hours

$hours = '12'
$jobname = 'ClearRecycleBin'
$user = 'azuread\patrickgruenauersid-'

New-Item $home\recyclebin.ps1 -Value 'Clear-RecycleBin -Force' -Force

$action =   New-ScheduledTaskAction -Execute `
            'powershell.exe' `
            -Argument "–file $home\recyclebin.ps1"
$settings = New-ScheduledTaskSettingsSet
$principal= New-ScheduledTaskPrincipal -UserId $user
$trigger =  New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours $hours)
$task =     New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings -Principal $principal

Register-ScheduledTask -TaskName $jobname -InputObject $task -Force

We will then find our task in taskschd.msc.

This brings me to option 2. PowerShell Scheduled Jobs.

Option 2: PowerShell Scheduled Jobs (recommended)

Another option is to create the task using PowerShell Scheduled Jobs. As you can see, we need less code and we do not need a file.

### This script creates a PowerShell ScheduledJob to clear the recycle bin every x hours

# RepititionInterval
$hours = '12' 
# JobName
$jobname = 'ClearRecycleBin' 
# UserAccount
$user = 'azuread\patrickgruenauersid-'

# Action
Register-ScheduledJob -Name $jobname -ScriptBlock `
{powershell.exe -NoProfile -NoLogo -Command "Clear-RecycleBin -Force -ErrorAction SilentlyContinue"} `
-Trigger (New-JobTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours $hours) -RepeatIndefinitely) `
-Credential $user

The location is different this time. We find the task in the Task Schedular in Microsoft – Windows – PowerShell – Scheduled Jobs.

That’s it for today. Hope this was helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.