Question

I'm writing a script that should empty the Recycle.Bin of all the devices / partitions attached to the computer.

It does this by testing the possible devices available (from a to z letter) excluding the ones that aren't connected.

The script doesn't work properly because of the IF statement inside a FOR loop. How can I get around this?

@echo off
Setlocal EnableExtensions EnableDelayedExpansion
FOR %%G IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO (
    SET nodev=none
    fsutil fsinfo volumeinfo "%%G:" | find "Errore:" > nul
    IF %ERRORLEVEL% EQU 0 SET nodev="%%G:"
    IF "%%G:" NEQ "%nodev%" (
        RD /s /q "%%G:\RECYCLED"
        RD /s /q "%%G:\RECYCLER"
        RD /s /q "%%G:\$Recycle.Bin"
    )
)
Was it helpful?

Solution 2

Try this instead of fsutil. Also its cleaner code wise.

@echo off
Setlocal EnableDelayedExpansion
FOR %%G IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO (
    cd /d "%%G:" 2>nul
    IF !ERRORLEVEL! EQU 0 (
        RD /s /q "%%G:\RECYCLED"
        RD /s /q "%%G:\RECYCLER"
        RD /s /q "%%G:\$Recycle.Bin"
    )
)

OTHER TIPS

There are a couple of issues.

Firstly you are setting the nodev variable with %'s around it, which you only use when accessing the variable.

Secondly you need to use delayed expansion to access that variable when inside a for loop by using !'s instead of %'s.

Try this instead

@echo off
Setlocal EnableDelayedExpansion
FOR %%G IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO (
SET nodev=none
fsutil fsinfo volumeinfo "%%G:" | find "Errore:" > nul
IF !ERRORLEVEL! EQU 0 SET nodev="%%G:"
IF "%%G:" NEQ "!nodev!" (
RD /s /q "%%G:\RECYCLED"
RD /s /q "%%G:\RECYCLER"
RD /s /q "%%G:\$Recycle.Bin"
)
)

Why not download a simple program like

EmptyRecycleBin.exe

Works perfectly

Use google for a link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top