Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch delete all files and directories except specified file and directory [duplicate]

Tags:

batch-file

cmd

I'm trying to delete all files and directories in a specific directory using a bat file in said directory. I've seen this done on Linux without problem, but in Windows command environment it seems to be a chore.

Example: \temp\1.bat (keep) \temp\special folder (keep)

Inside \temp\ contains all the folders and files I want to delete except the 1.bat and the special folder.

I have tried recursive commands but they delete the directory, or they delete all the files and keep the directories.

Example:

attrib +r "special directory"
attrib +r "1.bat"
erase /Q *.*
rd /s /q
attrib -r "1.bat"

But this remove everything. If I remove the rd line, it removes all the files, not the directories and keeps the 1.bat file (like I need).

I've also tried:

for /d %%i in (".\*") do if /i not "%%i"=="special folder" rd /s /q "%%i"

But this doesn't work either. I simply cannot get all the directories and files to be deleted except for the "special folder" and the "1.bat file".

Is this even possible?

like image 540
Jake J Avatar asked Jul 19 '19 08:07

Jake J


People also ask

How do I delete all files except a specific file extension?

Microsoft Windows Browse to the folder containing the files. Click the Type column heading to sort all files by the type of files. Highlight all the files you want to keep by clicking the first file type, hold down Shift , and click the last file.

How do you delete all files in a directory except some?

Using Extended Globbing and Pattern Matching Operators Also, with the ! operator, we can exclude all files we don't want glob to match during deletion. Let's look at the list of pattern matching operators: ?(pattern-list) matches at least zero and at most one occurrence.

What does %% mean in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.


2 Answers

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "keepfile=1.bat"
SET "keepdir=keep me"

FOR /d %%a IN ("%sourcedir%\*") DO IF /i NOT "%%~nxa"=="%keepdir%" RD /S /Q "%%a"
FOR %%a IN ("%sourcedir%\*") DO IF /i NOT "%%~nxa"=="%keepfile%" DEL "%%a"

GOTO :EOF

You would need to change the setting of sourcedir, keepdir and keepfile to suit your circumstances. The listing uses a setting that suits my system.

The for/d command deals with all of the directories, except that where the name+extension matches the required name, then the for repeats the action on files in the target directory, deleteing all except that which matches the required filename-to-keep.

like image 114
Magoo Avatar answered Oct 31 '22 19:10

Magoo


The following batch file could be used for this task:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "TargetFolder=%~1"
if not defined TargetFolder set "TargetFolder=."
set "ExcludeBatchFile="
for %%I in ("%TargetFolder%\") do if "%%~dpI" == "%~dp0" set "ExcludeBatchFile=/C:"%~nx0""
for /F "eol=| delims=" %%I in ('dir "%TargetFolder%\" /AD /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /L /V /X /C:"special folder"') do rd /S /Q "%TargetFolder%\%%I"
for /F "eol=| delims=" %%I in ('dir "%TargetFolder%\" /A-D /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /L /V /X /C:"1.bat" %ExcludeBatchFile%') do del /A /F "%TargetFolder%\%%I"
endlocal

for /F with dir is used instead of for /D to process also subdirectories with hidden attribute set. for /D ignores subdirectories with hidden attribute.

This batch file runs the directory cleanup on the directory passed as argument to the batch file. It makes the cleanup on current directory if batch file is started without any argument.

The batch file protects itself on being deleted on deleting files in current directory or in a specified target directory and batch file is in current directory or the specified target directory. But the batch file does not protect itself on being deleted if the batch file is stored in any subdirectory of the current directory or specified target directory.

There can be multiple /C:"Directory Name" arguments specified on second FOR command line to exclude multiple subfolders in target folder for being removed by the batch file.

There can be multiple /C:"File Name" arguments specified on third FOR command line to exclude multiple files in target folder for being removed by the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • del /?
  • dir /?
  • echo /?
  • endlocal /?
  • findstr /?
  • for /?
  • if /?
  • rd /?
  • setlocal /?

Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and |. The redirection operators > and | must be escaped with caret character ^ on both FOR command lines to be interpreted as literal characters when Windows command interpreter processes these command lines before executing command FOR which executes the embedded command line with dir and findstr with using a separate command process started in background using %ComSpec% /c and the specified command line.

like image 1
Mofi Avatar answered Oct 31 '22 18:10

Mofi