Windows batch script to delete everything in a fol

2019-01-11 19:37发布

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.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-11 19:59

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
查看更多
一纸荒年 Trace。
3楼-- · 2019-01-11 19:59

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

查看更多
The star\"
4楼-- · 2019-01-11 20:11

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
查看更多
登录 后发表回答