user3677103
user3677103

Reputation: 225

Delete all files in folder except file in list using batch

I have three file in a folder (temp folder) that are

1.txt
2.exe
3.txt

Now I will use to batch to write script for deleting all files in the folder except one file (3.txt). How to write it in script. I try to use

del temp /Q

But it will delete all file in my folder. I don't want to delete all. I only want to delete 1.txt and 2.exe. Let consider number of file is large.

Upvotes: 1

Views: 12494

Answers (2)

BuvinJ
BuvinJ

Reputation: 11046

If you loop through the contents of a directory, you can apply whatever logic you might want, and perform whatever operations you might want on those contents. Example:

@echo off

setlocal enableextensions enabledelayedexpansion

set dirPath=C:\Users\BuvinJ\Desktop\test

pushd !dirPath!

:: Loop through all files in this directory 
for %%a in (*) do (
    set fileName=%%a
    if "!fileName!"=="1.txt" (
        echo FOUND: !fileName!
    ) else (
        echo OTHER: !fileName!
    )
)

:: Loop through all sub directories in this directory
for /d %%a in (*) do (
    set dirName=%%a
    echo Directory: !dirName!
)

popd

You might also want to step through the contents "recursively", i.e. drilling down into the nested sub directories. To do so add /r after your for statement (like with the /d in the example to loop through directories instead of files).

For more on this kind of looping, check this out: http://ss64.com/nt/for2.html

Upvotes: 2

user3336190
user3336190

Reputation: 233

You can use the command

except 3.txt del temp /Q

It will delete all files in the folder except 3.txt

Upvotes: -1

Related Questions