Deleting from a Recycle Bin folder all items except certain file formats

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Deleting from a Recycle Bin folder all items except certain file formats

#1 Post by DOSadnie » 23 Aug 2022 12:20

Long story short: there are some issues with the Recycle Bin throughout iterations of Windows. Thus currently on Windows 10 when I want to be sure I am deleting all content from it I use such script

Code: Select all

rd /s /q c:\$Recycle.Bin
rd /s /q d:\$Recycle.Bin
rd /s /q e:\$Recycle.Bin
which removes these particular folders [thus does not deal with the Recycle Bin overall system folder]. And it works [99% of the time]


How about if I only wanted to delete e.g. all files and folders from a Recycle Bin located on volume D except files which are of music formats [like MP3, FLAC, WAV, APE]? What a proper code for such operation would look like - and would it really work for this problematic system folder?

And alternatively: is it also possible to leave out files of all formats that are not older than [lets say] 66 days?
Last edited by DOSadnie on 21 Jul 2023 13:13, edited 5 times in total.

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Deleting from a Recycle Bin folder all files except certain file formats

#2 Post by aGerman » 23 Aug 2022 15:15

The items in $Recycle.Bin are not what they appear to be. $Recycle.Bin is a special Shell folder. Everything is virtualized. You have to use another scripting language to get the data that you are looking for.
This JScript hybrid might give you an indication of how you could achive your tasks. Filter the data as you like, and use the path in %%j to delete the item that you don't want to keep anymore.

Steffen

Code: Select all

@if (0)==(0) echo off
:: ^^ Always the first line in the script.

for /f "tokens=1-6 delims=|" %%i in ('cscript.exe //nologo //e:jscript "%~f0"') do (
  echo ~~~~~~~~~~~~~~~~~~~~~~
  echo [F]ile or [D]irectory: %%i
  echo actual path:           "%%j"
  echo original path:         "%%k"
  echo days not modified:     %%l
  echo days displaced:        %%m
  if "%%i"=="F" echo size (files only^):     %%n
)

echo(
pause

:: vv Always the last lines in the script.
goto :eof @end
var FMTID_Displaced = '{9B174B33-40FF-11D2-A27E-00C04FC30871}', PID_DISPLACED_FROM = '2', PID_DISPLACED_DATE = '3', msInDay = 86400000,
  ssfBITBUCKET = 0xa, colItems = new ActiveXObject('Shell.Application').Namespace(ssfBITBUCKET).Items(), i = 0, objItem;
for (; i < colItems.Count; ++i) {
  objItem = colItems.Item(i);
  WScript.Echo((objItem.IsFolder && objItem.Name.slice(-4).toLowerCase() !== '.zip' ? 'D' : 'F') + '|' +
    objItem.Path + '|' +
    objItem.ExtendedProperty(FMTID_Displaced + PID_DISPLACED_FROM).replace(/\\$/,'') + '\\' + objItem.Name + '|' +
    Math.round((new Date() - new Date(objItem.ModifyDate)) / msInDay) + '|' +
    Math.round((new Date() - new Date(objItem.ExtendedProperty(FMTID_Displaced + PID_DISPLACED_DATE))) / msInDay) + '|' +
    objItem.Size);
}
Last edited by aGerman on 02 Sep 2022 05:21, edited 1 time in total.

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all files except certain file formats

#3 Post by DOSadnie » 31 Aug 2022 17:29

aGerman wrote:
23 Aug 2022 15:15
[...]
This JScript hybrid might give you an indication of how you could achive your tasks. Filter the data as you like, and use the path in %%i to delete the item that you don't want to keep anymore.
[...]
Until today I was not aware of existence of such scripts - thus I failed at doing this:

>>

Is the part before pause is suppose to look like this

Code: Select all

@if (0)==(0) echo off

for /f "tokens=1-3 delims=?" %%i in ('cscript.exe //nologo //e:jscript "%~f0"') do (
"%D:\$RECYCLE.BIN%i"
%txt%~xj
)
if I want to deleted only TXTs from Recycle Bin of D?

<<

And if the above code had worked, I would still need to do the opposite: leave [as a test] all TXTs and wipe out all non-TXTs
Last edited by DOSadnie on 01 Jul 2023 04:21, edited 2 times in total.

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Deleting from a Recycle Bin folder all files except certain file formats

#4 Post by aGerman » 02 Sep 2022 05:39

You actually only need to use the FOR variables, sometimes along with their modifiers. That's just Batch and is unrelated to the JScrip portion at the end of the code.
I updated the example above in order to get more data. The echo output shows the meaning of the FOR variables.

To achieve your original request, the FOR /F loop might look like that:

Code: Select all

for /f "tokens=1-6 delims=|" %%i in ('cscript.exe //nologo //e:jscript "%~f0"') do (
  REM take only the recycle bin of drive D: into consideration
  if /i "%%~dj"=="D:" (
    REM handle files and directories separately
    if "%%i"=="F" ( REM file
      REM doDelete is used like a flag; any value assigned to it is treated as "true"; initially it is explicitely undefined which is treated as "false"
      set "doDelete="
      REM any file with a different extension than those used in the IF chain will be marked for deletion
      if /i not "%%~xk"==".MP3" if /i not "%%~xk"==".FLAC" if /i not "%%~xk"==".WAV" if /i not "%%~xk"==".APE" set "doDelete=1"
      REM any file being longer than 66 days in recycle.bin will be marked for deletion (regardless of the file extension)
      if %%m gtr 66 set "doDelete=1"
      REM check the doDelete marker, and either delete or keep the file
      if defined doDelete ECHO del "%%j"
    ) else ( REM directory
      REM always delete directories
      ECHO rd /s /q "%%j"
    )
  )
)
There are two all-capitals ECHO commands which only output the command lines to be executed. Remove them in order to actually perform the tasks.

Addendum: You're doing something deliberately wrong as soon as you use the recycle bin as a temporary folder. The reason for the existence of recycle bin is to be able to restore files that are inadvertently deleted. You can bypass the recycle bin by pressing [Shift]+[Del] for marked items that you really want to delete immediately. And if you're not entirely sure whether or not you still want to keep them, better move them to an "obsolete" or an "old" folder where you tidy up every now and then.

Steffen

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all files except certain file formats

#5 Post by DOSadnie » 03 Jan 2023 05:03

aGerman wrote:
02 Sep 2022 05:39
Addendum: You're doing something deliberately wrong as soon as you use the recycle bin as a temporary folder.
No. It is just a case of combo of tasks that are performed almost daily and sheer volume of files their produce - resulting with rare but inevitable user mistakes occurring due to fatigue and tediousness

My often mass editing and converting of audio files leads to GBs of data, most of which is deleted within seconds or minutes or weeks afer creation of short or long time temporary files. All in all Recycle Bin gets bloated with dozens of GBs after a month or so. But very rarely some files or meta data which is discovered as being lost are also discovered by me as having succumbing to falling through the cracks of my both manual and automatic backup system. And so the Recycle Bin is the last resort in efforts of retrieving potentially hours of work that was performed even as far as months ago. And because also all kind of other stuff is deleted, thus alltogether it amounts to TBs of data. Thus a need to filter potentially important leftovers, temps and copies conveniently in a particular Recycle Bin [as audio is worked upon on two disks, each with just one volume]
aGerman wrote:
02 Sep 2022 05:39
[...]
better move them to an "obsolete" or an "old" folder where you tidy up every now and then.
That could be a modification of my modus operandi - but it would generate unnecessary clicks and for sure lead to a greater number of mistakes and would. It is just not worth it
Last edited by DOSadnie on 28 Dec 2023 05:58, edited 4 times in total.

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all files except certain file formats

#6 Post by DOSadnie » 03 Jan 2023 06:06

As for the quest
aGerman wrote:
02 Sep 2022 05:39
[...]
To achieve your original request
[...]
then if the whole script is suppose to look literally like this

Code: Select all

@if (0)==(0) echo off
:: ^^ Always the first line in the script.

:: This navigates to the folder containing the executable file and then runs it. So this simply opens the software
for /f "tokens=1-6 delims=|" %%i in ('cscript.exe //nologo //e:jscript "%~f0"') do (
  REM take only the recycle bin of drive D: into consideration
  if /i "%%~dj"=="D:" (
    REM handle files and directories separately
    if "%%i"=="F" ( REM file
      REM doDelete is used like a flag; any value assigned to it is treated as "true"; initially it is explicitely undefined which is treated as "false"
      set "doDelete="
      REM any file with a different extension than those used in the IF chain will be marked for deletion
      if /i not "%%~xk"==".MP3" if /i not "%%~xk"==".FLAC" if /i not "%%~xk"==".APE" set "doDelete=1"
      REM any file being longer than 66 days in recycle.bin will be marked for deletion (regardless of the file extension)
      if %%m gtr 66 set "doDelete=1"
      REM check the doDelete marker, and either delete or keep the file
      if defined doDelete del "%%j"
    ) else ( REM directory
      REM always delete directories
      rd /s /q "%%j"
    )
  )
)

echo(
pause

:: vv Always the last lines in the script.
goto :eof @end
var FMTID_Displaced = '{9B174B33-40FF-11D2-A27E-00C04FC30871}', PID_DISPLACED_FROM = '2', PID_DISPLACED_DATE = '3', msInDay = 86400000,
  ssfBITBUCKET = 0xa, colItems = new ActiveXObject('Shell.Application').Namespace(ssfBITBUCKET).Items(), i = 0, objItem;
for (; i < colItems.Count; ++i) {
  objItem = colItems.Item(i);
  WScript.Echo((objItem.IsFolder && objItem.Name.slice(-4).toLowerCase() !== '.zip' ? 'D' : 'F') + '|' +
    objItem.Path + '|' +
    objItem.ExtendedProperty(FMTID_Displaced + PID_DISPLACED_FROM).replace(/\\$/,'') + '\\' + objItem.Name + '|' +
    Math.round((new Date() - new Date(objItem.ModifyDate)) / msInDay) + '|' +
    Math.round((new Date() - new Date(objItem.ExtendedProperty(FMTID_Displaced + PID_DISPLACED_DATE))) / msInDay) + '|' +
    objItem.Size);
}
then it does not work; because it only sees in Recycle Bin of drive D only few graphics related files omitting whole bunch of other items]- and even for those it spits out Access is denied error. And these errors are manifestation of those
DOSadnie wrote:
23 Aug 2022 12:20
[...]
some issues with the Recycle Bin throughout iterations of Windows
[...]
that I mentioned in my initial post. To combat them I tried running BAT file with this script as Administrator, both with Run as Administrator applied to the file itself from the shell menu and to a LNK shortcut leading to it - and that second trick I use in order to successively run that overall script of mine
DOSadnie wrote:
23 Aug 2022 12:20
[...]

Code: Select all

rd /s /q c:\$Recycle.Bin
rd /s /q d:\$Recycle.Bin
rd /s /q e:\$Recycle.Bin
[...]
[thus it should make the BAT work but somehow it does not]

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all files except certain file formats

#7 Post by DOSadnie » 01 Jul 2023 07:18

I have managed to cook up this code

Code: Select all

:: This specifies the volumes and their respective Recycle Bin paths
set "volume=T W V"
set "recycleBinPath=\$Recycle.Bin"

:: List of file formats to be excluded
set "exclude=.ape .flac .m4a .mid .mp3 .wav .wv"

:: This applies the task to every volume specified on the first list [of volumes]
for %%D in (%volume%) do (

:: This changes directory to the Recycle Bin on the current volume
    cd /D "%%D:%recycleBinPath%"

::  This deletes for good all files - except those from the second list [of file formats]
    for /r %%A in (*) do (
        set "file=%%~xA"
        setlocal enabledelayedexpansion
        if "!exclude:%%~xA=!"=="!exclude!" (
            del "%%A" /f /q
        )
        endlocal
    )
)
and it works OK; i.e. it deletes all files from Recycle Bin folder on volumes specified in it - with the exception of those few audio formats also specified in it. But unfortunately it does not work A-OK, as it leaves out also folders in them, which should also be deleted; apparently because of that
The system cannot find the path specified.
as it repeatedly says

So how can I also delete just folders in a Recycle Bin - but without a need to specify them once more? I just cannot write in two places of this script the same volumes / paths, because it will be only a matter of time when somewhere in the future I will forget to add / remove a volume in the other line of my BAT and thus keep using it - until some day [when needed] to discover that I do not have deleted folders kept in a Recycle Bin of e.g. volume Z
Last edited by DOSadnie on 19 Jul 2023 11:23, edited 1 time in total.

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all files except certain file formats

#8 Post by DOSadnie » 04 Jul 2023 03:38

In other words, this script needs to be reworked so that:

1] it list volumes

2]
it deletes [specified] files in Recycle Bins on those volumes

3] it deletes folders in Recycle Bins also on those volumes

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all files except certain file formats

#9 Post by DOSadnie » 19 Jul 2023 15:49

DOSadnie wrote:
04 Jul 2023 03:38
In other words, this script needs to be reworked
[...]
I have managed to do that:

Code: Select all

set "LIST OF VOLUMES=A B C D E F G H I J K L N O P Q R S T U V W X Y Z"

set "PATH TO RECYCLE BIN=\$Recycle.Bin"

set "LIST OF EXCLUDED FILE FORMATS=.ape .cue .flac .m4a .mid .midi .mp3 .tta .wav .wv"

for %%D in (%LIST OF VOLUMES%) do (
    cd /D "%%D:%PATH TO RECYCLE BIN%"

:: This removes all files from a Recycle Bin folder - except those from the list of exempt file formats
    for /r %%A in (*) do (
        set "file=%%~xA"
        setlocal enabledelayedexpansion
        if "!LIST OF EXCLUDED FILE FORMATS:%%~xA=!"=="!LIST OF EXCLUDED FILE FORMATS!" (
            del "%%A" /f /q
        )
^
:: This removes all files from a Recycle Bin folder without extensions - which are created by system for folders that are deleted to Recycle Bin
        if "!file!"=="" (
            echo Deleting file: "%%A"
            del "%%A" /f /q
        )
        endlocal
    )
^
:: This removes all folders from a Recycle Bin folder
::
^    
    for /d /r %%A in (*) do (
        set "folder=%%A"
        rd /s /q "%%A"
    )
)
It on purpose omits volume M completely- thus applies itself to all other

And I also added to it process od deletion of the extension-less files, as they are created in a Recycle Bin folder whenever I delete some folder



But there are two problems with this otherwise working script:

A]
It unnecessarily for me omits files and folders that happen to have the hidden attribute

B] It only deletes extension-less from the very last volume that happens to be in a system at the time of execution of this BAT

So how can I mitigate these two issues?

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all items except certain file formats

#10 Post by DOSadnie » 11 Aug 2023 07:54

I made some progress

Code: Select all

@echo off

set "LIST OF VOLUMES=A B C T U V W X Y Z"
set "PATH TO A RECYCLE BIN=\$Recycle.Bin"
set "LIST OF EXCLUDED FILE FORMATS=.ape .cue .flac .m4a .mid .midi .mp3 .tta .wav .wv"

for %%D in (%LIST OF VOLUMES%) do (
    pushd "%%D:%PATH TO A RECYCLE BIN%"

    for /r %%A in (*) do (
        set "file=%%~xA"
        
        setlocal enabledelayedexpansion
        
        if "!LIST OF EXCLUDED FILE FORMATS:%%~xA=!"=="!LIST OF EXCLUDED FILE FORMATS!" (
            echo Deleting item: "%%A"
            echo.
            del "%%A" /f /q
        )
        
        if "!file!"=="" (
            echo Deleting item: "%%A"
            echo.
            del "%%A" /f /q
        )
        
        endlocal
    )
)

pause
This BAT removes from a Recycle Bin folder on selected volumes folders and files [including items which are hidden] but with exception of listed file formats. But it also unnecessarily goes through every item in the folder where this BAT is residing - and spits out for every one of them info
the system cannot find the drive specified.
deleting item: X
where that >>X<< is the full path to an item - but fortunately does not delete them

So how can I make this false info go away- but not by merely hiding it but by stopping this script from applying its deletion attempt to content of the folder in which this BAT is residing [i.e. make sure the deletion occurs only in Recycle Bin folder on only the selected volumes]?

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all items except certain file formats

#11 Post by DOSadnie » 28 Dec 2023 07:16

So does anyone know how to do this?

And also how make this latest version of ny script to apply itself also to the last volume present in the system, as apparently it ignores my volume W [which is my last]


I tried writing a corresponding PS1 script but failed miserably at it

Squashman
Expert
Posts: 4487
Joined: 23 Dec 2011 13:59

Re: Deleting from a Recycle Bin folder all files except certain file formats

#12 Post by Squashman » 28 Dec 2023 09:40

DOSadnie wrote:
03 Jan 2023 05:03
And so the Recycle Bin is the last resort in efforts of retrieving potentially hours of work that was performed even as far as months ago.
Wow. If I only had known all these decades that I could just use the recycle bin as a backup mechanism. This should literally bankrupt that software sector.

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all items except certain file formats

#13 Post by DOSadnie » 29 Dec 2023 11:01

Wow indeed, as apparently you have never ever accidentally deleted something and also never run out of disk space - thus never had to empty the Recycle Bin and never realized after some time that a re-worked item is missing. Wow

Or you just do not understand what last resort means

DOSadnie
Posts: 144
Joined: 21 Jul 2022 15:12
Location: Coding Kindergarten

Re: Deleting from a Recycle Bin folder all items except certain file formats

#14 Post by DOSadnie » 11 Feb 2024 04:43

DOSadnie wrote:
11 Aug 2023 07:54
I made some progress
[...]
But it also unnecessarily goes through every item in the folder where this BAT is residing - and spits out for every one of them info
[...]
I finally managed do take care of that - and on top of it also hid the
The system cannot find the drive specified.
messages showing up when a specified volume is not mounted in the system

Code: Select all

@echo off

set "LIST OF VOLUMES=A B C T U V W X Y Z"
set "PATH TO A RECYCLE BIN=\$Recycle.Bin"
set "LIST OF EXCLUDED FILE FORMATS=.ape .cue .flac .m4a .mid .midi .mp3 .tta .wav .wv"

for %%I in ("%~dp0.") do set "FOLDER_FROM_WHICH_THIS_SCRIPT_IS_EXECUTED=%%~fI"

for %%D in (%LIST OF VOLUMES%) do (
    pushd "%%D:%PATH TO A RECYCLE BIN%" 2>nul

    if not errorlevel 1 (
        for /r %%A in (*) do (
            set "file=%%~xA"
            
            setlocal enabledelayedexpansion
            
            if "!CD!"=="!FOLDER_FROM_WHICH_THIS_SCRIPT_IS_EXECUTED!" (
                echo Skipping deletion of an item in the script directory
            ) else (
                if "!LIST OF EXCLUDED FILE FORMATS:%%~xA=!"=="!LIST OF EXCLUDED FILE FORMATS!" (
                    echo Deleting item: "%%A"
                    echo.
                    del "%%A" /f /q
                )

                if "!file!"=="" (
                    echo Deleting item: "%%A"
                    echo.
                    del "%%A" /f /q
                )
            )
            
            endlocal
        )
    )
    popd
    
)

pause

Post Reply