如何编写Bat脚本保留指定文件夹并删除其余所有内容?
批量保留指定目录/文件并删除其余内容的Bat脚本解决方案
Hey there, let's get your batch script sorted so it does exactly what you need—keeping keep1 and keep2 (plus all their contents) while wiping out everything else in your target folder.
First, let's address the syntax issue in your original script: the if statements weren't properly chained, which would have caused the script to misbehave. Here's the corrected version that works reliably:
@echo off set "folder=c:\FTP\" set "keep=keep1" set "keeptwo=keep2" cd /d %folder% for /F "delims=" %%i in ('dir /b') do ( if /i "%%~ni" NEQ "%keep%" if /i "%%~ni" NEQ "%keeptwo%" ( rmdir "%%i" /s/q 2>nul || del "%%i" /s/q 2>nul ) ) pause
Quick breakdown of the fixes and logic:
- Clean variable definition: I moved the quotes outside the variable values to avoid extra quote marks messing up path references.
- Proper conditional chaining: The two
ifstatements are combined so the deletion only runs when the item's name is neitherkeep1norkeep2. The/iflag makes the check case-insensitive, so it works even if folder names have mixed capitalization. - Silent, robust deletion:
rmdir /s/qdeletes folders and all their sub-contents quietly.del /s/qhandles standalone files and files in subdirectories.2>nulsuppresses harmless error messages (like trying to delete a file withrmdiror a folder withdel—the||ensures the correct command runs regardless).
Testing with your directory structure:
Your target folder starts like this:
c:\FTP\ ├── folder1\ │ └── file1.txt ├── folder2\ │ └── file1.txt ├── keep1\ │ └── file1.txt ├── keep2\ │ └── file1.txt └── file1.txt
After running the script:
keep1andkeep2(and all their files) stay intactfolder1,folder2, and the standalonefile1.txtare fully removed—no leftover files or subfolders.
内容的提问来源于stack exchange,提问作者CZFox
相关产品推荐
相关产品推荐

