我在一个文件夹(临时文件夹)中有三个文件
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/