PowerShell Function: Clear-RecycleBin

How to Delete Items in the Recycle BinPowerShell Function Clear-Recyclebin

This page is dedicated to creating a PowerShell script to delete old files in the Recycle Bin.

I have created 3 variants of this function; my reasoning was to provide relatively harmless examples before you settle on a script which actually cleans-out the recycle bin.

Guy's Clear-RecycleBin Function

 ♣

Planning the Clear-RecycleBin Function

The brief is to remove the contents of the Recycle Bin.  However, I want to begin by merely listing the files in the bin, then we can progress to deleting items based on their age.

1) Create a Shell Application with a type of ComObject

$Shell= New-Object -ComObject Shell.Application

2) List the Methods available to the $Shell object, and thus discover 'Namespace'

Clear-Host
$Shell= New-Object -ComObject Shell.Application
$Shell | Get-Member | Sort-Object Name

Among $Shell's 30+ methods, as revealed by $Shell | Get-Member, is Namespace.  Enumerating the 'Titles' of these namespaces proved to be a challenge, but I found the Recycle Bin at number 10, see below:

3) Script to investigate Namespaces such as Recycle Bin

Clear-Host
$Shell= New-Object -ComObject Shell.Application
ForEach($i in $(0..65)){
$Shell.namespace($i) | Where-Object {$_.Title} |
Select-Object @{Label="Index";Expression={$i}}, Title,`
@{Label="Path";Expression={$_.Self.Path}}
}

Note 1: Observe the key-pair values in the hash table.

4) Actual Function to Delete Items in the Recycle Bin

Because it's easy to get carried away and delete files you did not intend, this script has several safety features. 

By default it just lists files older than 500 days.  To actually remove the files append the -Remove parameter.  Also the -Days parameter allows you to view or remove relatively young files. 

Function Global:Clear-RecycleBin {
<#
.SYNOPSIS
PowerShell function to list and delete old files in Recycle Bin
.DESCRIPTION
Includes -Delete parameter to remove old files.
.EXAMPLE
Clear-RecycleBin -Days 30
Clear-RecycleBin -Days 7 -Remove
#>
[cmdletbinding()]
Param (
[parameter(Mandatory=$false)]$Days=500,
[parameter(Mandatory=$false)][Switch]$Remove
)
Begin {
Clear-Host
$x=0
      } # End of small begin section
Process {
$Shell= New-Object -ComObject Shell.Application
$Bin = $Shell.NameSpace(10)
$Now = (Get-Date) -(New-TimeSpan -Days $Days)
ForEach($Item in $Bin.Items()) {
If($Now -gt $Item.ModifyDate) {
"{0,-22} {1,-20} {2,-20}" -f $Item.ModifyDate, $Item.Name, $Item.Path
$x++
} # End of first If
If($Remove){
If($Now -gt $Item.ModifyDate) {
"{0,-22} {1,-20} {2,-20}" -f $Item.ModifyDate, $Item.Name, $Item.Path
$x++
$Item | Remove-Item -Force
             } # End of If Now
           } # End of If Remove
        } # End of Foreach
    } # End of Process Section
End {
"`n Detected $x files older than $Days days"
"`n Removed = $Remove "
   } # End of 'End' section
} # End of Clear-RecycleBin Function

# Example of using this function:
Clear-RecycleBin

More Examples of Clear-RecycleBin

  1. Clear-RecycleBin -Days 14 # The default is 500 days.
  2. Note: This example deletes the old files in the bin.
    Clear-RecycleBin -Days 21 -Remove
  3. Help Clear-RecycleBin -Full

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Notes on My Clear-RecycleBin Function

1) Top Section – Help and Description
The function begins with a preamble: <# ….Adding Comments… #> Of particular interest is the help section.

2) PowerShell Parameters
Param(
The main rational for creating functions is to include parameters, and thus give the basic command flexibility.  In this example, the -Remove parameter is vital if the function is to achieve it's goal, namely to delete files in the recycle bin.

3) Process: Main Section
Process is a keyword to tell PowerShell where the action starts.  The crucial instruction is $Item | Remove-Item -Force.  I would consider adding the -Confirm parameter, the problem is that it can be annoying if there are numerous portions to the bin, for example a recycle bin on each drive.

4) Begin and End
These 2 keywords introduce optional sections, which could introduce one-off code.

Other Ideas for RecycleBin Functions

Create two Functions, Get-RecycleBin, like Clear-RecycleBin but without the -Remove parameter.  Change the existing Clear-RecycleBin so that it goes straight into deleting the files; if you do this then consider adding a -Confirm Parameter.

Get-RecycleBin Function

Function Global:Get-RecycleBin {
<#
.SYNOPSIS
PowerShell function to list files in Recycle Bin
.DESCRIPTION
Includes just lists recyclebin files with path
Note you can use the -Days parameter
.EXAMPLE
Get-RecycleBin
.EXAMPLE
Get-RecycleBin -Days 21
#>
[cmdletbinding()]
Param (
[parameter(Mandatory=$false)]$Days=1
)
Begin {
Clear-Host
$x=0
         } # End of small begin section
Process {
$Shell= New-Object -ComObject Shell.Application
$Bin = $Shell.NameSpace(10)
$Now = (Get-Date) -(New-TimeSpan -Days $Days)
ForEach($Item in $Bin.Items()) {
If($Now -gt $Item.ModifyDate) {
"{0,-22} {1,-20} {2,-20}" -f $Item.ModifyDate, $Item.Name, $Item.Path
$x++
                  } # End of 'If'
              } # End of Foreach
   } # End of Process Section
End {
"`n Detected $x files older than $Days days"
      } # End of 'End' section
} # End of Get-RecycleBin Function
Help Get-RecycleBin -Full

# Example of using this function:
Get-RecycleBin

Guy Recommends:  SolarWinds’ Log & Event Management ToolSolarwinds Log and Event Management Tool

LEM will alert you to problems such as when a key application on a particular server is unavailable.  It can also detect when services have stopped, or if there is a network latency problem.  Perhaps this log and event management tool’s most interesting ability is to take corrective action, for example by restarting services, or isolating the source of a maleware attack.

Yet perhaps the killer reason why people use LEM is for its compliance capability, with a little help from you, it will ensure that your organization complies with industry standards such as CISP or FERPA.  LEM is a really smart application that can make correlations between data in different logs, then use its built-in logic to take corrective action, to restart services, or thwart potential security breaches – give LEM a whirl.

Download your FREE trial of SolarWinds Log & Event Management tool.

Clear-RecycleBin Function (Pure)

Function Global:Clear-RecycleBin {
<#
.SYNOPSIS
PowerShell function to list and delete old files in Recycle Bin
.DESCRIPTION
Includes -Confirm parameter to check removal of old files.
.EXAMPLE
Clear-RecycleBin -Days 30
.EXAMPLE
Clear-RecycleBin -Days 60 -Confirm
#>
[cmdletbinding()]
Param (
[parameter(Mandatory=$false)]$Days=500,
[parameter(Mandatory=$false)][Switch]$Confirm
)
Begin {
Clear-Host
$x=0
            } # End of small begin section
Process {
$Shell= New-Object -ComObject Shell.Application
$Bin = $Shell.NameSpace(10)
$Now = (Get-Date) -(New-TimeSpan -Days $Days)
ForEach($Item in $Bin.Items()) {
If($Confirm){
If($Now -gt $Item.ModifyDate) {
"{0,-22} {1,-20} {2,-20}" -f $Item.ModifyDate, $Item.Name, $Item.Path
$Item | Remove-Item -Force -Confirm
$x++
              } # End of If
          } # End of Confirm
If($Now -gt $Item.ModifyDate) {
"{0,-22} {1,-20} {2,-20}" -f $Item.ModifyDate, $Item.Name, $Item.Path
$Item | Remove-Item -Force
$x++
           } # End of If
        } # End of Foreach
    } # End of Process Section
End {
"`n Removed $x files older than $Days days"
    } # End of 'End' section
} # End of Clear-RecycleBin Function

# Example of using this function:
Clear-RecycleBin -Days 21

Learning Points for Creating a PowerShell Function

  • From a scripting point of view, [Switch]$Confirm enables you to oscillate between running the basic command, and modifying the code as laid out in the IF($Confirm) {Swap this code} construction.
  • From a user's point of view, think of appending a -switch so that you can filter the action, for example:
    Clear-RecycleBin -Confirm

See more on PowerShell function parameters »

Summary of PowerShell Function to Clear-RecycleBin

My brief is to create a function which delete the contents of the Recycle Bin.  However, for safety reasons I have started with a function which merely lists the files in the bin.  From there, I explain how to modify the function so that it actually zaps unwanted files permanently.

If you like this page then please share it with your friends

 


See More PowerShell Function Parameters

Scripting PowerShell Function   • PowerShell Function Clear-Recyclebin   • PowerShell Get-File

Create PowerShell Function Get-ServiceStatus  • PowerShell Function Get-Driver  • PowerShell Outlook

Show-BalloonTip   • PowerShell Function Get-IPConfig   • Free Permissions Analyzer

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.