Linux – Prevent Windows from creating $RECYCLE.BIN folder on Samba share

linuxnetwork-sharessambawindows

Browsing a Samba share on a Windows machine, I notice after a short while that it has created a $RECYCLE.BIN folder in within the network share, usually containing a single desktop.ini file. How do I prevent my Windows clients from creating this file, either on the Samba server (Linux) or the Windows clients themselves?

Even if Windows creates the folder and I delete it on the server side, without deleting any other files, eventually the folder will re-appear (with desktop.ini inside of it). It's as if Windows is creating and deleting desktop.ini at random intervals.

A similar question asked how to prevent creation or hide this file, but I only want to know how to prevent creation.

Best Answer

Warning:

With this answer, I am not encouraging readers to delete Recycle Bin in their Windows OS. Recycle Bin helps to recover files/folder from accidental deletion. Do not attempt these steps in a working important PC.

Used trick:

Windows creates a hidden $RECYCLE.BIN folder for Recycle Bin in every mounted drives. Generally current logged-in user has no ownership of this folder. To delete this folder, user has to take ownership of it. After deleting this folder, Windows creates automatically after sometime. To prevent this, create a file of same name. Windows can't/don't override a file with a folder of same name.

Procedure:

Delete the Recycle Bin folder with these following commands as administrator. Let assume the drive letter is D:. Replace the drive letter as needed. Here are the steps:

  • Take ownership: Takeown /F "D:\$RECYCLE.BIN" /R /D Y
  • Change permission: Icacls "D:\$RECYCLE.BIN" /grant Everyone:(OI)(CI)(F) /T
  • Remove system attributes (optional): Attrib -R -S -H "D:\$RECYCLE.BIN" /S /D
  • Delete folder: Rmdir /S /Q "D:\$RECYCLE.BIN"
  • Create an empty file: echo.> "D:\$RECYCLE.BIN"

Alternatively, combine those steps in a single batch file (.bat) and run it as administrator:

@echo off
Takeown /F "D:\$RECYCLE.BIN" /R /D Y 
Icacls "D:\$RECYCLE.BIN" /grant Everyone:(OI)(CI)(F) /T 

REM This is a comment
REM Attrib -R -S -H "D:\$RECYCLE.BIN" /S /D 

Rmdir /S /Q "D:\$RECYCLE.BIN" & echo.> "D:\$RECYCLE.BIN"
pause

I combine the last two steps in one line so that Windows doesn't create that folder in meantime. To revert back, just delete the empty file and restart File Explorer.

Further details:

Related Question