windows Windows批处理脚本删除文件夹中除一个之外的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3008567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:37:29  来源:igfitidea点击:

Windows batch script to delete everything in a folder except one

windowscommand-linebatch-file

提问by Thomas K

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.

而且效果很好!唯一的问题是我想排除一个或多个文件夹,例如 XCOPY 排除功能。

I just cant figure how I could add that to the script.

我只是不知道如何将它添加到脚本中。

回答by Patrick

You could try to hide the folders before the for-loop, and unhide them afterwards, like this:

您可以尝试在 for 循环之前隐藏文件夹,然后取消隐藏它们,如下所示:

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

回答by user3918509

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

"%%i" 和 DEL 之间需要有一个 & 否则它会删除文件夹而不是文件。

回答by aschipfl

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