Sunday, May 19, 2024
HomePowershellEmpty the Recycle Bin with PowerShell and the Process Scheduler – SID-500.COM

Empty the Recycle Bin with PowerShell and the Process Scheduler – SID-500.COM


PowerShell

On this submit I’ll present you methods to empty the recycle bin mechanically. For this I’ll use PowerShell and Scheduled PowerShell Jobs. So I’ll present two methods how to do that (second one is really useful).

Possibility 1: Process Scheduler

The Process Scheduler is a function in Microsoft Home windows. We create a file and this file, which comprises Clear-RecycleBin, is executed based on our schedule. Right here is the code. Data have to be entered in line 3 to five.

### This script creates a Scheduled Process to clear the recycle bin each x hours

$hours="12"
$jobname="ClearRecycleBin"
$consumer="azureadpatrickgruenauersid-"

New-Merchandise $homerecyclebin.ps1 -Worth 'Clear-RecycleBin -Drive' -Drive

$motion =   New-ScheduledTaskAction -Execute `
            'powershell.exe' `
            -Argument "–file $homerecyclebin.ps1"
$settings = New-ScheduledTaskSettingsSet
$principal= New-ScheduledTaskPrincipal -UserId $consumer
$set off =  New-ScheduledTaskTrigger -As soon as -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours $hours)
$activity =     New-ScheduledTask -Motion $motion -Set off $set off -Settings $settings -Principal $principal

Register-ScheduledTask -TaskName $jobname -InputObject $activity -Drive

We’ll then discover our activity in taskschd.msc.

This brings me to choice 2. PowerShell Scheduled Jobs.

Possibility 2: PowerShell Scheduled Jobs (really useful)

An alternative choice is to create the duty utilizing PowerShell Scheduled Jobs. As you may see, we want much less code and we don’t want a file.

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

# RepititionInterval
$hours="12" 
# JobName
$jobname="ClearRecycleBin" 
# UserAccount
$consumer="azureadpatrickgruenauersid-"

# Motion
Register-ScheduledJob -Title $jobname -ScriptBlock `
{powershell.exe -NoProfile -NoLogo -Command "Clear-RecycleBin -Drive -ErrorAction SilentlyContinue"} `
-Set off (New-JobTrigger -As soon as -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours $hours) -RepeatIndefinitely) `
-Credential $consumer

The placement is completely different this time. We discover the duty within the Process Schedular in Microsoft – Home windows – PowerShell – Scheduled Jobs.

That’s it for as we speak. Hope this was useful.

Revealed by Patrick Gruenauer

Microsoft MVP on PowerShell [2018-2023], IT-Coach, IT-Marketing consultant, MCSE: Cloud Platform and Infrastructure, Cisco Licensed Academy Teacher.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments