Search code examples
for-loopbatch-filesearchcmdtraversal

Batch Script Search & Delete all folders that match name "*Cache*" but leave out certain paths from traversal


As I asked in Q-title, how can I traverse the whole %SYSTEMDRIVE% root folder for any directory that contains *Cache* in it's name and fully purge that directory inside-out but leave out certain paths from such traverse-delete, such as %APPDATA%\npm ?

I have the following command for traversing and deleting all folders containing Cache(case-insensitive) in their name and delete those completely:

pushd "%SYSTEMDRIVE%"
for /d /r %%a in ("*Cache*") do if exist "%%a" ( echo "%%a" & rd /s /q "%%a" )
popd

But I want to skip looking into %APPDATA%\npm completely, how can I achieve that ?

Note: OS: Windows 10 64Bit


Solution

  • @ECHO Off
    SETLOCAL
    pushd "%SYSTEMDRIVE%\"
    for /d /r %%a in ("*cache*") do if exist "%%a" ECHO "%%a"|FINDSTR /i /L /c:"%appdata%\npm\" >NUL&IF ERRORLEVEL 1 (echo delete "%%a") ELSE (echo skip "%%a")
    POPD
    GOTO :EOF
    

    First issue : you need to pushd to the root directory of your drive, otherwise you will select the currently-logged directory on that drive.

    Then simply echo the directoryname found to findstr to see whether that name contains the directoryname to exclude. The name needs to be quoted to allow for names containing &. Findstr looks for a /i case-Insensitive /L Literal match to the constant-string contained in appdata. with the subdirectotyname appended, and a backslash appended to that so that it does not match against "...\npmnotamatch".

    If findstr finds a match, errorlevel is set to 0 so the directory should be skipped, else delete.

    Be very, very careful. Please see Caution regarding directorynames