Chris
Chris

Reputation: 677

How to delete files and sub-folders from folders not starting with a specific name in a batch file?

I have a directory of D:\data which has many folders containing data from map layers (D:\data\parks, D:\data\buildings, D:\data\rivers).

I want to delete the contents of all of these sub-folders which includes both files and sub-folders, except any folders within 'data' that start with the name 'raster' i.e

D:\data\raster_aerialimage .

I have some code which deletes one of the folders, but I need to loop through all folders and specify only folders that do not start with 'raster', how can I append this code, or should I start with something brand new?

FOR /D %%p IN ("D:\data\parks\*.*") DO rmdir "%%p" /s /q

Upvotes: 1

Views: 136

Answers (2)

aschipfl
aschipfl

Reputation: 34909

You could use dir /A:D to walk through all the directories together with findstr to return only those directories that do not start with raster. Then use a for /F loop to parse the output:

pushd "D:\data"
if ErrorLevel 1 goto :EOF
for /F "eol=| delims=" %%P in ('
    dir /B /A:D "*.*" ^| findstr /L /V /I /B /C:"raster"
') do (
    rmdir /S /Q "%%~fP"
)
popd

Upvotes: 1

user1016274
user1016274

Reputation: 4209

I suggest using robocopy.exe which is available in all newer Windows versions:

@echo off
set folder=D:\data
set except=raster
set "MT=%TEMP%\DelFolder_%RANDOM%"

mkdir %MT%
:: mirror an empty dir to a folder tree will delete it
robocopy "%MT%" "%folder%" /MIR /XD %except%* /R:1 /W:1
rmdir /S /Q "%MT%"

Note the wildcard star just behind the %except%variable.

It's fast and it copes with very long pathnames.

Upvotes: 1

Related Questions