'How to add multiple files in this same batch line
This code is used to remove all files and folders from the c:\test directory except "FolderA"
@echo off
pushd "C:\test" || exit /B 1
for /D %%D in ("*") do (
if /I not "%%~nxD"== "FolderA" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
In case I want to omit more than one folder, how could I add it? i mean delete everything except FolderA FolderB and Folder C (Names can contain spaces)
this doesn't work
@echo off
pushd "C:\test" || exit /B 1
for /D %%D in ("*") do (
if /I not "%%~nxD"== "FolderA" "FolderB" "Folder C" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
Solution 1:[1]
For a few items I would probably use this code:
@echo off
pushd "C:\test" || exit /B 1
for /D %%D in ("*") do (
set "ITEM=%%~nxD"
cmd /V /D /C echo(!ITEM!| findstr /V /X /I /C:"FolderA" /C:"FolderB" /C:"Folder C" 2> nul && rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
For numerous items I would put their names into a text file, a name per line, say exclude.txt:
FolderA FolderB Folder C
and then I would use this code:
@echo off
pushd "C:\test" || exit /B 1
for /D %%D in ("*") do (
set "ITEM=%%~nxD"
cmd /V /D /C echo(!ITEM!| findstr /V /X /I /L /G:"exclude.txt" 2> nul && rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
If you want to avoid slow pipes |, you could also use the following for loop approach, which avoids long if chains like if /I not "%%~nxD"=="FolderA" if /I not "%%~nxD"=="FolderB" if /I not "%%~nxD"=="Folder C" …:
@echo off
pushd "C:\test" || exit /B 1
for /D %%D in ("*") do (
set "FLAG=#"
for %%I in ("FolderA" "FolderB" "Folder C") do (
if /I "%%~nxD"=="%%~I" set "FLAG="
)
if defined FLAG rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aschipfl |
