-1

Need a bit help here please...

need a script preferably batch script to delete $recycle.bin folder in all sub folders.

I have Drive where I have user folders and each user folder has his own $recycle.bin folder.

Structure on Drive C:\
User1 > $recycle.bin
User2 > $recycle.bin
User3 > $recycle.bin

When user deletes something on his profile then it sends to c:\user1\$recycle.bin. At the moment I go in each folder separately to delete $recycle.bin.

Rossi
  • 23
  • 1
  • 7

1 Answers1

2

Use this more or less single line batch file with folder path C:\ to be replaced by real parent folder path:

@echo off
for /F %%D in ('dir "C:\$recycle.bin" /AD /B /S 2^>nul') do rd /Q /S "%%D" 2>nul

The command line above searches for folder $recycle.bin recursively in all directories of drive C: and deletes each found $recycle.bin.

There is also a second solution which is faster because of searching first only for non hidden folders in root of drive C: (user folder) and searching next in each found (user) folder for a folder $recycle.bin which is deleted if such a subfolder is really found in a user folder.

@echo off
for /D %%U in ("C:\*") do (
    for /F %%D in ('dir "%%U\$recycle.bin*" /AD /B 2^>nul') do rd /Q /S "%%U\%%D" 2>nul
)

The third solution is using second solution without searching for $recycle.bin in a user folder and instead simply assume that there is such a folder and delete it. If the subfolder of root of drive C: does not have a folder $recycle.bin an error message is output by command RD, but this error message is suppressed as explained below.

@echo off
for /D %%D in ("C:\*") do rd /Q /S "%%D\$recycle.bin" 2>nul

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • dir /?
  • echo /?
  • for /?
  • rd /?

See also Microsoft article Using command redirection operators for an explanation of 2>nul.

The error message output by command DIR to STDERR on not finding any folder with name $recycle.bin is suppressed by redirecting the error message to device NUL with 2>nul. The redirection operator > must be escaped with ^ to be applied on execution of command DIR instead of being interpreted as redirection of command FOR specified at an invalid position which would result in an exit of command processing because of a syntax error.

2>nul is also used on command RD to suppress the error message output on any folder or file inside the folder is currently in use by a user and therefore the deletion of the folder fails. On third solution it also suppress the error message if there is no folder $recycle.bin at all.

Mofi
  • 46,139
  • 17
  • 80
  • 143