You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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 if statements are combined so the deletion only runs when the item's name is neither keep1 nor keep2. The /i flag makes the check case-insensitive, so it works even if folder names have mixed capitalization.
  • Silent, robust deletion:
    • rmdir /s/q deletes folders and all their sub-contents quietly.
    • del /s/q handles standalone files and files in subdirectories.
    • 2>nul suppresses harmless error messages (like trying to delete a file with rmdir or a folder with del—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:

  • keep1 and keep2 (and all their files) stay intact
  • folder1, folder2, and the standalone file1.txt are fully removed—no leftover files or subfolders.

内容的提问来源于stack exchange,提问作者CZFox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:20:55