Site icon Think PowerShell

PowerShell Script to Empty Recycle Bin at Logoff

Windows Recycle Bin
Windows Recycle Bin

Automate the emptying of the Windows Recycle Bin with this simple PowerShell script and Group Policy.

Redirected Folders = Recycle Bin Storage on File Server

In a lot of business environments, we redirect user folders like Documents, Desktops, Favorites, and more to a home directory on a network share, often mapped to its own drive letter. The folders are then synced to the user’s workstation to be available offline. This gives the user the ability to work on the files when disconnected, but still allows IT to have the files stored on the file servers and backed up.

Managing user storage can be a challenge. What is worse is that a lot of a user’s storage can actually be in a hidden Recycle Bin folder in their home share. As far as a user’s concerned, when they’ve deleted a file from a folder it is gone, but it goes to an interim location in the Recycle Bin. If the file was in a redirected folder, the Recycle Bin storage is likewise redirected to the file share.

This is a hidden folder a server admin wouldn’t normally see, unless using a tool like WinDirStat to analyze the file shares. I have seen cases were users have GIGABYTES of files sitting in their Recycle Bin, some of them months old.

Automate Emptying of Recycle Bin at Logoff

To remedy this, the Technet ScriptCenter has this simple script you can configure to run at logoff via User Group Policy. When the user logs off, it will empty all items in the user’s Recycle Bin. This script is compatible with Windows 7 / Windows Server 2008 R2 and up.

# Clear-RecycleBinItems.ps1
$Shell = New-Object -ComObject Shell.Application 
$RecycleBin = $Shell.Namespace(0xA) 
$RecycleBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}

New Windows 10 Cmdlet: Clear-RecycleBin

The Clear-RecycleBin cmdlet was introduced in Windows 10 / PowerShell 5.0. The cmdlet lets you specify the letter drive from which you want to purge Recycle Bin contents. You could replace the script above with a one-liner script using this cmdlet.

Reference

 

PS C:\Users\aaron> Get-Help Clear-RecycleBin

NAME
    Clear-RecycleBin
    
SYNOPSIS
    
    
    
SYNTAX
    Clear-RecycleBin [[-DriveLetter] [<String[]>]] [-Force] [-InformationAction {SilentlyContinue | Stop | Continue | Inquire | Ignore | Suspend}] [-InformationVariable [<String>]] [<CommonParameters>]
    
    
DESCRIPTION
     

RELATED LINKS

REMARKS
    To see the examples, type: "get-help Clear-RecycleBin -examples".
    For more information, type: "get-help Clear-RecycleBin -detailed".
    For technical information, type: "get-help Clear-RecycleBin -full".

 

Exit mobile version