windows - 使用批处理删除文件夹中除列表中文件之外的所有文件

标签 windows string batch-file

我在一个文件夹(临时文件夹)中有三个文件

1.txt
2.exe
3.txt

现在我将使用批处理编写删除文件夹中除一个文件(3.txt)之外的所有文件的脚本。如何在脚本中编写它。我尝试使用

del temp /Q

但它会删除我文件夹中的所有文件。我不想全部删除。我只想删除 1.txt 和 2.exe。假设文件数量很大。

最佳答案

如果您遍历目录的内容,您可以应用您可能需要的任何逻辑,并对这些内容执行您可能需要的任何操作。示例:

@echo off

setlocal enableextensions enabledelayedexpansion

set dirPath=C:\Users\BuvinJ\Desktop\test

pushd !dirPath!

:: Loop through all files in this directory 
for %%a in (*) do (
    set fileName=%%a
    if "!fileName!"=="1.txt" (
        echo FOUND: !fileName!
    ) else (
        echo OTHER: !fileName!
    )
)

:: Loop through all sub directories in this directory
for /d %%a in (*) do (
    set dirName=%%a
    echo Directory: !dirName!
)

popd

您可能还想“递归”地遍历内容,即向下钻取到嵌套的子目录。为此,请在您的 for 语句之后添加/r(例如示例中的/d 以遍历目录而不是文件)。

有关这种循环的更多信息,请查看:http://ss64.com/nt/for2.html

关于windows - 使用批处理删除文件夹中除列表中文件之外的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24077336/

相关文章:

date - 从具有特定日期格式的批处理文件创建 txt 文件

windows - 如何在 Windows 中使用 xcopy 复制目录结构

c++ - LoadLibrary调用DLL时查找依赖的DLL

c# - Windows 8 应用程序 WebView 捕获事件目标 ="_blank"

windows - 为什么某些字符代码缺少 Windows-125* 编码中的字符?

c# - 如何在 if 语句中使用 != 和字符串数组?

python - 如何在 Python 中检测非 ASCII 字符?

通过命令行的 Windows 照片查看器 - 特殊功能

c++ - ICU Unicode 正常与全角

git - 我的批处理脚本只能第二次运行