Batch Script – Sending Items to the Recycle Bin Without Calling Any Third-Party Applications

While writing another larger script, I wanted the ability to send folders or files to the Recycle Bin, which I found out you can’t do natively via the command line without using some third-party apps or PowerShell.

I also found that when looping through a list of files in a batch script, it makes it really difficult to delete folders versus files because you have to either use the “del” command for files or the “rmdir” command for folders. With no simple way to differentiate between the two without a bunch of extra code, I kept looking for an alternative solution.

Following the rabbit trail further, I then discovered that you could use the “move” command to try and put the files in C:\$Recycle.Bin\<UsersSID>. That led me to find a one-liner on how to get the User’s SID, just to come to find that the moved files will not even show up in Explorer and emptying the trash doesn’t actually get rid of the files.

At last, following the same theory I applied in the larger script I was working on, I finally found some VB script that I could sort of embed into my little batch script to do what I needed and was able to contain it all within a single batch file.

Here’s the code:

:: Instead of deleting the files, we will send them to the current user's Recycle Bin but again
:: there is no native way to do this with the command prompt so we need yet another VB script.
:: This will auto-create the recycle.vbs script in the current directory the batch file is being ran from.
@ECHO InputPath = WScript.Arguments(0)>"%~dp0recycle.vbs"
@ECHO Set objShell = CreateObject("Shell.Application")>>"%~dp0recycle.vbs"
@ECHO Set Item = objShell.Namespace(0).ParseName(InputPath)>>"%~dp0recycle.vbs"
@ECHO Item.InvokeVerb("delete")>>"%~dp0recycle.vbs"

:: The path to our new recycle script dealie whopper
SET RScriptPath="%~dp0recycle.vbs"

Same as my previous post that is almost identical, you can call it like this:

CScript //nologo %RScriptPath% "PathOfFolderOrFileToDelete"

Then when you’re done, dispose of the evidence:

DEL /F /Q /S %RScriptPath%

Leave a Reply