0

I have seen a lot of variations of my situation but can't find one I'm comfortable with (very inexperienced). Basically I have a folder (E:\Downloads) that folders get added to and also contains a batch file (Extractor.bat). I would like to, once a week, delete all folders and files from within E:\Downloads but NEVER delete Extractor.bat. Thanks for any help on this! (The once a week part isn't necessary in the script, I know I can just set a windows task to run the bat file on specified days).

Windows 10

  • Two ideas: 1)Move/copy the batch file within the script itself, delete all files then move back move %~dp0 ..\ del *.* move ..\%~dp0 .\ 2)consider using Powershell which has an exclusion switch: Remove-Item -Path * -Exclude $PSCommandPath – gregg Feb 4 at 19:26
2

See the Set DEBUG=echo line?

Disable this line with REM or :: when you are sure that it is doing what you want it to do. This script is harmless while it exists.. not so much if you remove it.

The if /i not "%DownloadsDir%" == "%CD%" line comes from being stupid and blowing away all of my files in the wrong directory when I was younger and dumber.

Also.. you could change the cd /d to pushd and put a popd at the bottom if you are running this within cmd.exe and it messes up your current path.

@echo off
SetLocal
Set DEBUG=echo

Set DownloadsDir=E:\Downloads

cd /d %DownloadsDir%
if /i not "%DownloadsDir%" == "%CD%" echo Bad directory! && goto :EOF

for /F "delims=" %%d in ('dir /ad /b') do %DEBUG% rd /s /q "%%d"
for %%f in (*.*) do if /i not "%%f"=="Extractor.bat" %DEBUG% del /F /Q "%%f"

EndLocal
|improve this answer|||||
  • This worked to perfection, thank you very much!! – Mike Feb 4 at 19:21
  • Please feel free to mark this as the correct answer then ;) And you are very welcome. – Señor CMasMas Feb 4 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.