Windows batch script to delete everything in a folder except one - windows

I have a script to delete all subfolders and files in a folder:
FOR /D %%i IN ("D:\myfolder\*") DO RD /S /Q "%%i" & DEL /Q "D:\myfolder\*.*"
And it works great!
Only problem is that I would like to exclude one or more folders, like the XCOPY exclude feature.
I just cant figure how I could add that to the script.

You could try to hide the folders before the for-loop, and unhide them afterwards, like this:
ATTRIB +H D:\myfolder\keepit
FOR /D %%i IN ("D:\myfolder\*") DO RD /S /Q "%%i" DEL /Q "D:\myfolder\*.*"
ATTRIB -H D:\myfolder\keepit

there needs to be an & just between "%%i" and DEL or else it will delete folders but not files.

Here is a way that does not touch the excluded file and/or directory, so no attributes are altered:
rem // Change to target directory (skip if not found):
pushd "D:\Data" || exit /B 1
rem // Iterate through all subdirectories:
for /D %%D in ("*") do (
rem // Exclude a certain subdirectory:
if /I not "%%~nxD"=="ExcludeDir" rd /S /Q "%%~D"
)
rem // Iterate through all immediate files:
for %%F in ("*") do (
rem // Exclude a certain file:
if /I not "%%~nxD"=="ExcludeFile.txt" del "%%~F"
)
popd

Related

Delete all files in directory except .bat

I want to delete a specific directory on Windows. I use the code below. It works fine. I want to put the .bat file I made for this process in that directory. Naturally, the .bat file is also deleted. I want the .bat file to be excluded from this deletion. What should I do with the code?
Echo batch file delete folder
#RD /S /Q "D:\testfolder"
All you have to do is to lock your batch file, by opening a dummy read handle to it.
echo The batch file wont be deleted because it is locked by a dummy input redirection.
rd /s /q "D:\testfolder" 9<"%~f0"
Naturally, an error message will be shown by the rd command, because there is at-least one file in the target directory (your own batch file) which can not be deleted. You can hide that message by redirecting the standard error stream to the nul device:
rd /s /q "D:\testfolder" 9<"%~f0" 2>nul
There are several ways to achieve your task.
The method, (especially as you generally remove directories with one command, and delete files with another), is to identify the files and subdirectories separately. First identify the subdirectories and remove those, using the RD command, then delete all files except for the batch file itself, %0:
You could do that in one line using the ForFiles utility:
#%SystemRoot%\System32\forfiles.exe /P "%~dp0." /C "%SystemRoot%\System32\cmd.exe /C If #IsDir==TRUE (RD /S /Q #File) Else If /I Not #file == \"%~nx0\" Del /A /F #File"
Or you could use a For loop, with the Dir command:
#For /F Delims^=^ EOL^= %%G In ('Dir /B /A "%~dp0"') Do #If "%%~aG" GEq "d" (RD /S /Q "%%G") Else If /I Not "%%G" == "%~nx0" Del /A /F "%%G"
Please note that you can only remove/delete items for which you have the required permissions.
I would walk through the items in the folder whose contents you want to delete, remove one after another, except its name equals the name of the batch file:
rem // Change into target directory:
pushd "%~dp0." && (
rem /* Loop through immediate children of the target directory, regarding even
rem hidden and system items; to ignore such (replace `/A` by `/A:-H-S`): */
for /F "delims= eol=|" %%I in ('dir /B /A "*"') do (
rem // Check name of current item against name of this batch script:
if /I not "%%~nxI"=="%~nx0" (
rem /* Assume the current item is a sub-directory first (remove by `rd`);
rem when removal fails, try to delete it as a file (done by `del`): */
rd /S /Q "%%I" 2> nul || del /A /F "%%I"
)
)
rem // Return from target directory:
popd
)

Windows Batch Scripting: Delete All Files Inside A Folder Except

Hey i want to delete all files inside a folder except for few files, now these files i want to keep are normal folders & some of them are just blank files.
my files that i want to be kept
heres my current code, it keeps 1 folder only but i want to keep all 3 of the folders + my 2 blank files.
pushd "C:\Folder2" || exit /B 1
for /D %%D in ("*") do (
if /I not "%%~nxD"=="Important Folder1" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
[Edit /] (from comment section)
I tried, like this:
pushd "%LOCALAPPDATA%\Google\ChromeVoter\User Data\Default\" || exit /B 1
for /D %%D in ("*") do (
if /I not "%%~nxD"=="Important Folder1" rd /S /Q "%%~D"
if /I not "%%~nxD"=="Important Folder2" rd /S /Q "%%~D"
if /I not "%%~nxD"=="Important Folder3" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
It didn't work.

Delete all files that are set to hidden or read only or system

I want to remove all the jpg, ini and more types in current folder and all the sub folders, then delete all the empty folders (recursively). Some of those files are either read only or hidden or even set to system so just the del /s *.jpg doesn't remove them. The problem is it looks like the syntax is using logic and when I do: del /a:h /a:r /s *.jpg so only read only and hidden files are removed but not only hidden files. Is there a way to make it use logic or instead?
I couldn't find examples to make it work without copy pasting the same lines with small changes.
About rmdir, do I have to do cd to the current folder? because it says there's a syntax error in the code below:
del /s *.jpg
del /a:h /a:r /s *.jpg
rmdir /s /q
pause
EDIT3: I think that now it deletes everything with: del /s /f /a:h /a:a *.jpg
I found this for removing empty folders but it doesn't work if the folder is set to read only:
https://superuser.com/a/39679/451485
Not tested, but I believe the following will work:
#echo off
:: Remove readonly / hidden / system attributes from all files of interest
attrib -r -h -s *.jpg /s
attrib -r -h -s *.ini /s
rem etc...
:: Delete the files of interest
del /s *.jpg *.ini
:: for each folder, sorted descending by full path (children come before parent)
for /f "delims=" %%F in ('dir /b /ad /s *^|sort /r') do (
REM check if folder is empty
dir /b /a "%%F" | findstr "^" >nul || (
REM remove directory with /S /Q works, even if folder is read only
rd /s /q "%%F"
)
)

a batch file to delete a folder which is inside another folder

On windows 7, How can i write a batch file to delete a folder which is inside another folder.
this 'another folder' name varies.
Eg: C:\Users\%USERNAME%\AppData\Local\Mozilla\Firefox\Profiles\xxxxxx\cache2
the 'xxxxxx' might change. Now, i want to delete the 'cache2' folder and all its contents.
i tried this:
:: Batch script to clear browsing history, download history, and empty the cache for Mozila Firefox.
:: Script can be run via GFI MAX RM
#echo off
TASKKILL /T /F /IM Firefox.exe
set DataDir=C:\Users\%USERNAME%\AppData\Local\Mozilla\Firefox\Profiles
del /q /s /f "%DataDir%"
rd /s /q "%DataDir%"
for /d %%x in (C:\Users\%USERNAME%\AppData\Roaming\Mozilla\Firefox\Profiles\*) do del /q /s /f %%x\*sqlite
start "" "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
cls
IF %ERRORLEVEL%==0 (
#echo "Success Message"
timeout 10
) ELSE (
#echo "Error Message"
timeout 10
exit 1001
)
but this is deleting the entire profiles folder.
can anyone out there please help me out with this.
for /d %%a in (
"C:\Users\%USERNAME%\AppData\Local\Mozilla\Firefox\Profiles\*"
) do if exist "%%~fa\cache2\" echo rmdir /s /q "%%~fa\cache2"
For each folder under the Profiles folder, if it contains a cache2 subfolder, remove it.
rmdir commands are only echoed to console. If the output is correct, remove the echo command
simple:
rmdir /s C:\Users\%USERNAME%\AppData\Local\Mozilla\Firefox\Profiles\xxxxxx\cache2
If you know that your cache2 folder is a direct child of xxxxxx, then MC ND has a good answer. But if cache2 can appear at any level, then the following works, providing that cache2 is not a direct decendent of "...\Profiles\".
#echo off
for /f "delims=" %%F in ('dir /b /ad /s "C:\Users\%USERNAME%\AppData\Local\Mozilla\Firefox\Profiles\cache2"') do echo rd /s /q "%%F"
If cache2 can be a direct child of "...\Profiles", then the following should work as long as there are no folders with a name like "cache2.x".
#echo off
for /f "delims=" %%F in ('dir /b /ad /s "C:\Users\%USERNAME%\AppData\Local\Mozilla\Firefox\Profiles\cache2.?"') do echo rd /s /q "%%F"
Both commands above simply ECHO the RD statements. Simply remove ECHO when all looks correct.

Delete all files and folders in a directory

I want to have a batch file that will delete all the folders and files in my cache folder for my wireless toolkit.
Currently I have the following:
cd "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS"
del *.db
This will delete all .db files in my RMS directory, however I want to delete every single thing from this directory. How can I do this?
Use:
Create a batch file
Copy the below text into the batch file
set folder="C:\test"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
It will delete all files and folders.
del *.* instead of del *.db. That will remove everything.
IF EXIST "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" (
rmdir "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" /s /q
)
This will delete everything from the folder (and the folder itself).
I just put this together from what morty346 posted:
set folder="C:\test"
IF EXIST "%folder%" (
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)
It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.
del *.* will only delete files, but not subdirectories. To nuke the contents of a directory, you can use this script:
#echo off
setlocal enableextensions
if {%1}=={} goto :HELP
if {%1}=={/?} goto :HELP
goto :START
:HELP
echo Usage: %~n0 directory-name
echo.
echo Empties the contents of the specified directory,
echo WITHOUT CONFIRMATION. USE EXTREME CAUTION!
goto :DONE
:START
pushd %1 || goto :DONE
rd /q /s . 2> NUL
popd
:DONE
endlocal
The pushd changes into the directory of which you want to delete the children. Then when rd asks to delete the current directory and all sub directories, the deletion of the sub directories succeed, but the deletion of the current directory fails - because we are in it. This produces an error which 2> NUL swallows. (2 being the error stream).
You can do this using del and the /S flag (to tell it to recurse all files from all subdirectories):
del /S C:\Path\to\directory\*
The RD command can also be used. Recursively delete quietly without a prompt:
#RD /S /Q %VAR_PATH%
Rmdir (rd)
set "DIR_TO_DELETE=your_path_to_the_folder"
IF EXIST %DIR_TO_DELETE% (
FOR /D %%p IN ("%DIR_TO_DELETE%\*.*") DO rmdir "%%p" /S /Q
del %DIR_TO_DELETE%\*.* /F /Q
)
Use
set dir="Your Folder Path Here"
rmdir /s %dir%
mkdir %dir%
This version deletes without asking:
set dir="Your Folder Here"
rmdir /s /q %dir%
mkdir %dir%
Example:
set dir="C:\foo1\foo\foo\foo3"
rmdir /s /q %dir%
mkdir %dir%
This will clear C:\foo1\foo\foo\foo3.
(I would like to mention Abdullah Sabouin's answer. There was a mix up about me copying him. I did not notice his post. I would like to thank you melpomene for pointing out errors!)
Try the following; it works for me.
I have an application which dumps data in my "C:\tmp" folder, and the following works the best for me. It doesn't even ask Yes or No to delete the data. I have made a schedule for it to run after every 5 minutes
cd "C:\tmp"
del *.* /Q
Better yet, let's say I want to remove everything under the C:\windows\temp folder.
#echo off
rd C:\windows\temp /s /q
You could use robocopy to mirror an empty folder to the folder you are clearing.
robocopy "C:\temp\empty" "C:\temp\target" /E /MIR
It also works if you can't remove or recreate the actual folder.
It does require an existing empty directory.
I would like to suggest using simple tool like cleardir. So, in batch file you can write:
cleardir path/to/dir
And you'll get empty directory dir. A bit slow, but still resolves the "problem".
I'm an author of the tool =)
The easiest way is:
Create *.txt file
Write:
rmdir /q /s . dir
Save file as *.bat in folder which you want to clear (you can call the file NUKE.bat)
Turn it on
WARNING!
THIS DELETES EVERYTHING IN THE FOLDER WHERE IT IS WITHOUT ASKING FOR CONFIRMATION!!!
SO CHOOSE WISELY PLACE FOR SAVING IT.
Easy simple answer :
C:
del /S /Q C:\folderName\otherFolderName\*
C: Important in case you have to switch from D: to C: or C: to D: (or anything else)
/S Recursive, all subfolders are deleted along
/Q If you don't activate quiet mode, prompt will ask you to type y for every subfolders... you don't want that
Be carful, it's drastic.
You cannot delete everything with either rmdir or del alone:
rmdir /s /q does not accept wildcard params. So rmdir /s /q * will error.
del /s /f /q will delete all files, but empty subdirectories will remain.
My preferred solution (as I have used in many other batch files) is:
rmdir /s /q . 2>NUL
Just a modified version of GregM's answer:
set folder="C:\test"
cd /D %folder%
if NOT %errorlevel% == 0 (exit /b 1)
echo Entire content of %cd% will be deleted. Press Ctrl-C to abort
pause
REM First the directories /ad option of dir
for /F "delims=" %%i in ('dir /b /ad') do (echo rmdir "%%i" /s/q)
REM Now the files /a-d option of dir
for /F "delims=" %%i in ('dir /b /a-d') do (echo del "%%i" /q)
REM To deactivate simulation mode remove the word 'echo' before 'rmdir' and 'del'.
#echo off
#color 0A
echo Deleting logs
rmdir /S/Q c:\log\
ping 1.1.1.1 -n 5 -w 1000 > nul
echo Adding log folder back
md c:\log\
You was on the right track. Just add code to add the folder which is deleted back again.

Resources