set target="C:\Documents and Settings\username\My Documents"
if not exist %target% GOTO ERROR
cd %target%
if not exist temp2 md temp2
if not exist temp2 GOTO ERROR
copy *.txt temp2
echo Y | del *.*
cd temp2
copy *.txt ..\*.txt
echo Y | del *.*
cd ..
rd temp2
:ERROR
goal:
Simple batch file that deletes all files/folders in specific folder EXCEPT files with a certain file extension?
(Elegant solution preferred)
@echo off
@ attrib +h +r %3\%1 /S
@ %2 %3 /Q /S
@ attrib -h -r %3\%1 /S
@ goto :EOF
do you want to traverse the tree down through folders and still delete files there based on the certain file extension?"
It should delete ANYTHING (files, folders) except files of a certain file-type in the root folder. What's *in* the specific folders is not of interest, if it sees a folder the folder can be entirely deleted.
@echo off
@ attrib +h +r %3\%1 /S
@ %2 %3 /Q /S
@ attrib -h -r %3\%1 /S
@ for /f "tokens=*" %%d in ('dir %3 /ad/b/s ^| sort /R') do rmdir "%%d" /s /q 2>nul || (echo Not empty: %%d)
@ goto :EOF
You state files/folders, but do you want to traverse the tree down through folders and still delete files there based on the certain file extension? Or do you only want to delete any folder that exists plus all the non matching files?
This will delete all files except those specified by the first parameter passed recursively through folders:
To use call it like this: <name of bat file>.bat *.<extension to keep> del "<folder to delete from>"Code:@echo off @ attrib +h +r %3\%1 /S @ %2 %3 /Q /S @ attrib -h -r %3\%1 /S @ goto :EOF
here's an example to delete all but pdf files in c:\test
test.bat *.pdf del "c:\test"
Postmark, thank you for the great solution. I was wondering, if I wanted to use this, but wanted it to exclude more than one extension, could you tell me how to do so? Thanks