Black Mamba
Black Mamba

Reputation: 245

Delete files, folders and sub-folders but skipping files that cointain certain string

Just tried to clean the temp folder of Windows and it inside folders, skipping all files that contains TESTE in it name.

@echo off
pushd "%WinDir%\TEMP" && (
    for /F "delims= eol=|" %%F in ('
        dir /B /A:-D "*.*"
    ') do (
        set "NAME=%%~nF"
        setlocal EnableDelayedExpansion
        if /I "!NAME:TESTE=!"=="!NAME!" (
            endlocal
            del /F /Q "%%F"
            rd /F /S /Q "%%F"               
            md %windir%\temp
        ) else endlocal
    )
    popd
)

It's say that F is wrong to deleting the folder.

This is a complement of this question: Delete all files in a folder but skip files that cointain certain string

Upvotes: 0

Views: 123

Answers (2)

Compo
Compo

Reputation: 38589

Here's a basic untested single line example, which may be sufficient for your purposes:

@"%__APPDIR__%Robocopy.exe" "%SYSTEMROOT%\Temp" "%SYSTEMROOT%\Temp" "*TESTE*.*" /S /Move 1> NUL

This will most likely require to be run elevated, due to your directory being a protected OS location.

Upvotes: 0

aschipfl
aschipfl

Reputation: 34899

The rd command does not feature an /F option.

Anyway, here is how I would modify the script to achieve your goal of keeping all files with the string TESTE in their base names, even in sub-directories (if I got it right):

@echo off
rem // Change into the target directory:
pushd "%WinDir%\TEMP" && (
    rem // Loop through all files in the target directory, recursing into sub-directories:
    for /F "delims= eol=|" %%F in ('
        dir /S /B /A:-D "*.*"
    ') do (
        rem // Store the base name of the current file:
        set "NAME=%%~nF"
        rem // Toggle delayed expansion to avoid troubles with `!`:
        setlocal EnableDelayedExpansion
        rem // Check whether the base name of the current file contains the string `TESTE`:
        if /I "!NAME:TESTE=!"=="!NAME!" (
            rem // Sub-string `TESTE` not encountered, so do some stuff at this point:
            endlocal
            rem // Delete the current file:
            del /F /Q "%%F"
            rem // Attempt to delete its parent directory when it is empty:
            rd "%%F\.." 2> nul
        ) else endlocal
    )
    rem // Return fro the target directory:
    popd
)

Upvotes: 1

Related Questions